Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the order of List items conditionally with LINQ

Tags:

c#

linq

i'm getting a list of items with 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'm getting the list as,

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

ordered by Code

now, my expected result is as below,

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

i know that i can get the expected result either by modifying the sql table containing these values or by adding an extra numeric column to the table specifying the sequence order.

is it possible to get the results with the help of LINQ without modifying the table?

like image 552
user3085995 Avatar asked Mar 05 '14 11:03

user3085995


1 Answers

So you want OTHER to be at the last position?

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

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

orderby p.DESC == "OTHER"  ? 1 : 0 ascending
like image 135
Tim Schmelter Avatar answered Sep 21 '22 23:09

Tim Schmelter