Reordering List Items Conditionally Using LINQ

I get a list of items with the following LINQ expression,

var list = (from p in listData orderby p.Code ascending select new KeyValuePair<int, string>(p.Code, p.DESC) ).Distinct<KeyValuePair<int, string>>().ToList<KeyValuePair<int, string>>(); 

I get the list as

 2,MEDICAL 5,RETAIL 6,OTHER 7,GOVT 

sorted by Code

now my expected result will be as below

 2,MEDICAL 5,RETAIL 7,GOVT 6,OTHER 

I know that I can get the expected result either by changing the sql table containing these values, or by adding an additional column number to the table indicating the order of the sequence.

Is it possible to get results using LINQ without changing the table?

+6
source share
1 answer

So do you want OTHER be in last position?

 from p in listData orderby p.DESC == "OTHER" ascending, p.Code ascending 

This works because true "higher" than false , maybe you will find this more readable:

 orderby p.DESC == "OTHER" ? 1 : 0 ascending 
+10
source

All Articles