Dynamic Linq Order By user defined sequence

dynamic-linq linq sorting sql-order-by

Question

I have dynamic linq query with OrderBy.

 .AsQueryable().OrderBy("FullName", asc)

After sorting by FullName, I need to sort by status (something like ThenBy()). Status may have vales e.g. "A", "B", "C", "D" But I need to sort in following sequence "B", "A", "D", "C". As result can't use asc/desc in this case.

1
1
6/26/2012 3:15:34 PM

Popular Answer

You need to do the following:

a) Define the collection of your keys in the order you want

var keys = new string[]{"B", "A", "D", "C"};

b) Use the above keys to define the custom order of your data

var result = yourCollection.AsQueryable()
                           .OrderBy("FullName", asc)
                           .ThenBy(x=>keys.IndexOf(x.Status));
2
6/26/2012 3:27:19 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow