Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq most efficient method

Tags:

c#

linq

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

like image 408
Nate Pet Avatar asked Apr 29 '26 00:04

Nate Pet


2 Answers

Try this:

var data = db.tbl1
  .Where(w => clientIds == clientid && (source == "All" || w.Source == source));
like image 180
mattytommo Avatar answered Apr 30 '26 13:04

mattytommo


@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);
like image 28
Dustin Laine Avatar answered Apr 30 '26 13:04

Dustin Laine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!