If condition in LINQ Where clause

前端 未结 8 1989
星月不相逢
星月不相逢 2020-12-03 06:56

Can I use if clause with Linq where?

相关标签:
8条回答
  • 2020-12-03 07:13

    Make use of WhereIf extenstion method avaialbe in linq

    Example

    if (SearchControlMain.PostingID.HasValue) 
        query = query.Where(q => q.PostingID == SearchControlMain.PostingID);
    

    instead of above go for the below

    query = query.WhereIf(SearchControlMain.CategoryID.HasValue, q => q.CategoryID == SearchControlMain.CategoryID);
    

    LINQ WhereIf Extension Method

    LINQ to SQL Where Clause Optional Criteria

    0 讨论(0)
  • 2020-12-03 07:14

    In my case there were two "conditional" where depending on search keys, so I did:

        var query = db.Package.Include("SomeThing")
        .Where(item => searchString1 == null || searchString1 == "" || item.Contains(searchString1))
        .Where(item => searchString2 == null || searchString2 == "" || item.Contains(searchString2));
        ...
    
    0 讨论(0)
  • 2020-12-03 07:17
    from item in items
    where condition1
    && (condition2 ? true : condition3)
    select item
    

    This is how can you can do it with the noob Linq syntax. This applies the condition3 only if condition2 is false. If condition2 is true, you are essentially doing && true which has no effect on the where clause.

    So it is essentially doing this:

    if(condition2)
    {
        from item in items
        where condition1
        select item
    else
    {
        from item in items
        where condition1
        && condition3
        select item
    }
    
    0 讨论(0)
  • 2020-12-03 07:22
    var query = someList.Where(a => (someCondition)? a == "something" : true);
    

    so, if 'someCondition' is false, 'Where' will be skipped.

    0 讨论(0)
  • 2020-12-03 07:23

    I had a scenario like this where I had to check for null within the list itself. This is what I did.

    items = from p in items
            where p.property1 != null   //Add other if conditions
            select p;
    
    // Use items the way you would use inside the if condition
    

    But as Kelsey pointed out this would work too -

    items = items.Where(a => a.property1 != null);
    
    0 讨论(0)
  • 2020-12-03 07:25

    Yes you can like:

    var query = someList.Where(a => a == "something");
    if (condition)
    {
        query = query.Where(b => b == "something else");
    }
    var result = query.ToList();
    

    Because Where is producing an IQueryable, the execution is deferred until the ToList in my example so you can chain Wheres together as much as you want and then just execute it after you have passed all your conditions.

    0 讨论(0)
提交回复
热议问题