Search code examples
entity-frameworklinq

How to use ternary operator linq where clause


Table : Id, Name,Subject,Score

1   Pinky    English   60
2   Pinky    Maths     40
3   Mahesh   Maths     50
4   Rani     Maths     50
5   Rani     Eco       50

I want to fetch record from table ,when Subject is maths, need record whose score should be more than 50,for remaining subject no condition.

Output :

1   Pinky   English   60
3   Mahesh  Maths     50
4   Rani    Maths     50
5   Rani    Eco       50

I tried like this :

var r = dbContext.Table1
                 .Where(x => x.Subject == "Maths" && 
                             x.Score >= 50 || 
                             x.Subject != "Maths");

It is working sometime but before above clause, there are few more filter as well base on role,subject get removed

How to write condition using ternary operator , when subject is Maths, then only fetch the record whose score is greater than or equal to 50.

(from tbl in dbContext.Table1 
 where tbl.Subject =='Maths' ? tbl.Subject =='Maths'
    && tbl.Score >= 50 : false  select tbl)

Is this


Solution

  • You're probably just seeing the effects of operator precendence - || has higher precendence than &&, so you need to put parentheses around the && clause:

    var r = dbContext.Table1
                     .Where(x => (x.Subject == "Maths" && x.Score >= 50) || 
                                 x.Subject != "Maths");
    

    which is logically equivalent to:

    var r = dbContext.Table1
                     .Where(x => x.Score >= 50 || x.Subject != "Maths");
    

    or, using a ternary operator:

    var r = dbContext.Table1
                     .Where(x => (x.Subject == "Maths") ? x.Score >= 50 : true);
    

    Use whichever one you think will make more sense if you were to look at it again a week later...