Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

ascending/descending in LINQ - can one change the order via parameter

By: a guest on Feb 27th, 2012  |  syntax: None  |  size: 1.12 KB  |  views: 40  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. var ascendingQuery = from data in dataList
  2.                       orderby data.Property ascending
  3.                       select data;
  4.  
  5. var descendingQuery = from data in dataList
  6.                       orderby data.Property descending
  7.                       select data;
  8.        
  9. public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
  10.     (this IEnumerable<TSource> source,
  11.      Func<TSource, TKey> keySelector,
  12.      bool descending)
  13. {
  14.     return descending ? source.OrderByDescending(keySelector)
  15.                       : source.OrderBy(keySelector);
  16. }
  17.  
  18. public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
  19.     (this IQueryable<TSource> source,
  20.      Expression<Func<TSource, TKey>> keySelector,
  21.      bool descending)
  22. {
  23.     return descending ? source.OrderByDescending(keySelector)
  24.                       : source.OrderBy(keySelector);
  25. }
  26.        
  27. var query = dataList.OrderByWithDirection(x => x.Property, direction);
  28.        
  29. var qry = from .... // or just dataList.AsEnumerable()/AsQueryable()
  30.  
  31. if(sortAscending) {
  32.     qry = qry.OrderBy(x=>x.Property);
  33. } else {
  34.     qry = qry.OrderByDescending(x=>x.Property);
  35. }