17

I'm trying to figure out a way of querying an object in my datamodel and include only those parameters that are not null. Like below:

public List<Widget> GetWidgets(string cond1, string cond2, string cond3)
{
    MyDataContext db = new MyDataContext();
    List<Widget> widgets = (from w in db.Widgets
                            where 
                                ... if cond1 != null w.condition1 == cond1 ...
                                ... if cond2 != null w.condition2 == cond2 ...
                                ... if cond3 != null w.condition3 == cond3 ...
                            select w).ToList();
    return widgets;
}

Since the widgets table can get very large, I'd like to avoid doing this:

public List<Widget> GetWidgets(string cond1, string cond2, string cond3)
{
    MyDataContext db = new MyDataContext();
    List<Widget> widgets = db.Widgets.ToList();

    if(cond1 != null)
        widgets = widgets.Where(w => w.condition1 == cond1).ToList();

    if(cond2 != null)
        widgets = widgets.Where(w => w.condition2 == cond2).ToList();

    if(cond3 != null)
        widgets = widgets.Where(w => w.condition3 == cond3).ToList();

    return widgets;
}

I've looked at several example but don't really see anything that matches what I need to do.

5 Answers 5

35

What you want to avoid is actually executing the query until you are ready:

public List<Widget> GetWidgets(string cond1, string cond2, string cond3)
{
    MyDataContext db = new MyDataContext();
    var widgets = db.Widgets;

    if(cond1 != null)
        widgets = widgets.Where(w => w.condition1 == cond1);

    if(cond2 != null)
        widgets = widgets.Where(w => w.condition2 == cond2);

    if(cond3 != null)
        widgets = widgets.Where(w => w.condition3 == cond3);

    return widgets.ToList();
}

Note how the ToList calls are removed. The query is not executed until you start iterating over it. Invoking ToList will force that to happen, so that the result can be put into a List<> and returned. I would even suggest to change the return value of the method to IEnumerable<Widget> and skipping the ToList call in the end:

public IEnumerable<Widget> GetWidgets(string cond1, string cond2, string cond3)
{
    MyDataContext db = new MyDataContext();
    var widgets = db.Widgets;

    if(cond1 != null)
        widgets = widgets.Where(w => w.condition1 == cond1);

   // [...]

    return widgets;
}

That way the calling code gets to decide when to execute the query (it may even add more conditions before doing so).

5
  • Is it up to the JIT compiler to get rid of the conditionals in the resulting query? Or does linq 'guarantee' some optimizations?
    – xtofl
    Commented Sep 21, 2010 at 16:51
  • @xtofl: not sure what you mean? What conditionals would you want to get rid of? Commented Sep 21, 2010 at 17:49
  • If the conditions are not met, they are not added to the expression tree.
    – Michael
    Commented Sep 22, 2010 at 2:02
  • I was wrong. I forgot that the linq query is constructed before execution, and as Michael says: the 'optional' conditions are not in the query's expression tree.
    – xtofl
    Commented Sep 22, 2010 at 11:05
  • @xtofl my code that failed to run in 64KB (yes, KB) of RAM is working fine using linq query. I don't get what magic is in linq. Commented May 16, 2018 at 10:47
27

Use an "or gate": preface every widget condition test with an "||" and a check to see if we're using that condition or not. If we're not, the second half of the "or" isn't evaluated. That's why it's a gate -- we don't go any further if the first part evaluates to true.

If I were writing it, I'd do it like below. I used the var syntatic sugar to hold LINQ query and moved the ToList() to the end.

public List<Widget> GetWidgets(string cond1, string cond2, string cond3) 
{ 
    MyDataContext db = new MyDataContext(); 
    var widgets = from w in db.Widgets 
                  where (cond1 == null || w.condition1 == cond1)
                     && (cond2 == null || w.condition2 == cond2)
                     && (cond3 == null || w.condition3 == cond3)
                  select w;
    return widgets.ToList();
} 

edit: grammar

4
  • 1
    This is the best solution and will be executed all in one SQL statement.
    – cmartin
    Commented Jan 22, 2016 at 12:59
  • 1
    This is the better solution, and +1 for pointing out the ToList part. Commented Aug 4, 2016 at 20:09
  • Easier to understand than the ambiguous English in the accepted answer. This is the working answer for me! Commented Apr 26, 2017 at 8:19
  • This is definitely the best answer! Commented Sep 25, 2017 at 14:43
2

How about something like this?

        IEnumerable<Widget> condQuery = (from w in db.Widgets);
        if(cond1 != null ) condQuery = condQuery.Where(w=> w.condition1 == cond1);
        if(cond2 != null ) condQuery = condQuery.Where(w=> w.condition2 == cond2);

etc...?

0
1

You're actually asking for a dispatcher within the linq query. The Where method takes a predicate, so you can build your predicate before creating the query.

-- EDIT -- at first, I thought it easier, wrote some pseudo code that didn't even compile. Now, howver, I think I got the point. This code will work; it separates building the where clause from applying it.

    static Predicate<Widget> combine( 
           Predicate<Widget> existing, 
           Predicate<Widget> condition )
    {
        var newpred = new Predicate<Widget>( w=> existing(w) && condition(w) );
        return newpred;

    }

and use this 'building' functionality like that:

    static void Main(string[] args)
    {
        string cond1 = "hi";
        string cond2 = "lo";
        string cond3 = null;
        var pr = new Predicate<Widget>( (Widget w ) => true );
        if (cond1 != null) pr = combine( pr, w => w.condition1 == cond1);
        if (cond2 != null) pr = combine( pr, w => w.condition2 == cond2);
        if (cond3 != null) pr = combine( pr, w => w.condition3 == cond3);

I tested it with a little helper array:

        var widgets = new Widget[]{
            new Widget (){ condition1 = "" },
            new Widget (){ condition1 = "hi", condition2 = "lo" }
        };

        var selected = widgets.Where( (w) => pr(w));

        foreach (var w in selected) {
            Console.WriteLine(w);
        }
8
  • Also, changes the logic. OP checks all non-null conditions, this only checks the first. OP also said that the conditions are strings, while this treats them as booleans.
    – curveship
    Commented Sep 21, 2010 at 14:19
  • Even if you did fix the compilation errors (strings are not implicitly convertible to bool), this version of the program has very different semantics than the original version. This version finds the first condition that can be tested and uses only it; the original version applied all possible conditions. Commented Sep 21, 2010 at 14:21
  • Your new version is better. I note that you've taken a slightly different tack than the other answers. Here you build up the predicate and then make a single Where clause, instead of making three predicates and three Where clauses. One minor improvement you could still make here is that the way you've written the query is bizarre. The combination of query syntax with "fluent" syntax looks weird, the trivial query is unnecessary and the predicate to Where is unnecessarily complicated. Commented Sep 21, 2010 at 15:43
  • I would have written either "var selected = from w in widgets where pr(w) select w;", or "var selected = widgets.Where(pr);" Commented Sep 21, 2010 at 15:44
  • 2
    Indeed; if we had to go back and do it again, I suspect that the type system designers would have structural typing on delegate types. The idea that a Func<T, bool> and a Predicate<T> are different types that are not compatible seemed like a good idea at the time but has turned out to be rather painful in practice. Commented Sep 21, 2010 at 17:49
1

we can use very simple way like below.

(from e in employee
join d in departments on e.departmentId equals d.departmentId
Select new {
e.name,
d.name,
getEmployeeContacts(e)
}
//return active contact if not return first . This is same like if else along with null check
private contact getEmployeeContacts(Employee e )
{
 return e.Contacts.FirstOrDefault(x => x.Active == 1) ?? e.Contacts.FirstOrDefault();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.