skip to Main Content

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

2

Answers


  1. Lambdas in Linq are just like functions — you can just use if statements and make it easy to read.

    var r = dbContext.Table1
                     .Where(x => 
                            {
                              if (x.Subject == "Maths")
                              {
                                if (x.Score >= 50)
                                   return true;
                                else
                                   return false;
                               }
                               return false;
                            });
    
    Login or Signup to reply.
  2. 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");
    

    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…

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search