Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement inside Where on LINQ

Tags:

c#

linq-to-sql

assume I have customer table with ( name column and number column) user can do query to display the one name's number or display all number if there is no restrict ;

this example

    void DisplayNumbersOfName(string name)
     {
        using (dataclassDataContext db = new dataclassDataContext())
           {
               if(name=="")
               var Names = from ta in db.table_accounts

                           select ( ta );
                else
                Names = from ta in db.table_accounts
                           where ta.name = name
                           select ( ta );

        }
     }

I don't want use this way because the method is

more complex , I want only change on 'where ' WHERE with IF

like image 876
Fadi Avatar asked Nov 18 '25 06:11

Fadi


2 Answers

You should use the fact that LINQ queries compose nicely - and that you don't need to use the query expression syntax. So:

// Fixing naming conventions as I go, to make the code more idiomatic...
using (DataClassDataContext db = new DataClassDataContext())
{
    IQueryable<YourDataType> query = db.TableAccounts;
    if (name != "")
    {
        query = query.Where(ta => ta.Name == name);
    }
    // Use query here...
}

walther's solution is another viable alternative, but it does mean evaluating the "do we really want this as part of the query" in the database - you'll end up with SQL which is somewhat harder to understand. Personally I prefer to be explicit about whether you want a particular filter to be part of the query.

like image 69
Jon Skeet Avatar answered Nov 20 '25 21:11

Jon Skeet


 void DisplayNumbersOfName(string name)
 {
    using (dataclassDataContext db = new dataclassDataContext())
    {
        var Names = from ta in db.table_accounts
                    where (String.IsNullOrEmpty(name) || ta.name == name)
                    select ( ta );

    }
 }

Haven't checked it to be honest, but it should work.

like image 30
walther Avatar answered Nov 20 '25 21:11

walther



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!