OrderBy
OrderBy is nice, except if you want to sort by multiple properties or want an easy way to distinguish between ascending and descending.
Source
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> enumerable, Func<TSource, TKey> keySelector, bool descending)
{
if (enumerable == null)
{
return null;
}
if (descending)
{
return enumerable.OrderByDescending(keySelector);
}
return enumerable.OrderBy(keySelector);
}
public static IOrderedEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> enumerable, Func<TSource, IComparable> keySelector1, Func<TSource, IComparable> keySelector2, params Func<TSource, IComparable>[] keySelectors)
{
if (enumerable == null)
{
return null;
}
IEnumerable<TSource> current = enumerable;
if (keySelectors != null)
{
for (int i = keySelectors.Length - 1; i >= 0; i--)
{
current = current.OrderBy(keySelectors[i]);
}
}
current = current.OrderBy(keySelector2);
return current.OrderBy(keySelector1);
}
public static IOrderedEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> enumerable, bool descending, Func<TSource, IComparable> keySelector, params Func<TSource, IComparable>[] keySelectors)
{
if (enumerable == null)
{
return null;
}
IEnumerable<TSource> current = enumerable;
if (keySelectors != null)
{
for (int i = keySelectors.Length - 1; i >= 0; i--)
{
current = current.OrderBy(keySelectors[i], descending);
}
}
return current.OrderBy(keySelector, descending);
}
Example
bool descending = (sortDirection = SortDirection.Descending);
PersonGridView.DataSource = persons.OrderBy(descending, p => p.Age, p => p.Name, p => p.Gender).ToList();
Author: Adam Weigert
Submitted on: 3 mrt. 2008
Language: C#
Type: System.Collections.Generic.IEnumerable<T>
Views: 12236