FrankTan
FrankTan

Reputation: 1686

Linq ordering result by number of Null

i have a query which return me the followin results

level_1_srg_key level_2_srg_key level_3_srg_key
NULL            NULL            1
NULL            1               NULL
NULL            1               1
1               NULL            NULL
1               NULL            1
1               1               NULL
1               1               1
1               2               1
1               2               3
3               1               1

this is the linq query:

    var query = from t in dbContext.SYSTEM_BEHAVIOURAL_W
                            where l.Contains(t.SRG_KEY)
                            group t by
                                new
                                {
                                    t.LEVEL_1_SRG_KEY,
                                    t.LEVEL_2_SRG_KEY,
                                    t.LEVEL_3_SRG_KEY
                                }
                                into grp
                            select
                            grp.Key;

i need to order this results first by rows which have 2 NULL after rows which have 1 NULL after rows which have 0 NULL

how to do this ?

Upvotes: 1

Views: 61

Answers (1)

Antonín Lejsek
Antonín Lejsek

Reputation: 6103

query = query.OrderBy(t => 
      (t.LEVEL_1_SRG_KEY == null ? 0 : 1) 
    + (t.LEVEL_2_SRG_KEY == null ? 0 : 1) 
    + (t.LEVEL_3_SRG_KEY == null ? 0 : 1));

Upvotes: 3

Related Questions