简体   繁体   中英

Linq most efficient method

I have need to use Linq statement as following

      var data = db.tbl1
      .Where(w => clientIds == clientid && w.Source == source);

I have a dropdown where I am getting source from. The dropdown values are as such:

All
NewsPaper
Web

The thing is NewsPaper and Web are valid values for Source. All is not. All means that a record can be NewsPaper or Web.

If they choose All, how do I modify w.Source such that All means NewsPaper or Web. I can do 2 seperate queries as shown below but rather not:

    if(source == "All")
    {
       var data = db.tbl1
      .Where(w => clientIds == clientid);
    }
    else
    {
       var data = db.tbl1
      .Where(w => clientIds == clientid && w.Source == source);
    }

I like to do it in 1 query as the query I have is actually more complicated than what is shown above.

Thank you in advance

Try this:

var data = db.tbl1
  .Where(w => clientIds == clientid && (source == "All" || w.Source == source));

@mattytommo answer is acceptable, but I prefer to break them out a bit. IMO a little more readable.

var data = db.tbl1.Where(w => clientIds == clientid);

if (source != "All")
    data = data.Where(w => w.Source == source);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM