Search code examples
c#linqienumerablequery-performanceiqueryable

Use WhereIf for multiple condition in c#


Hi can someone help me how best we can use whereif in LINQ, here I have a code which works fine, but I want to convert this query with WhereIf.

    public async Task LoadQuery(IEnumerable<string> codes)
    {
        var query = _dBContext.QueryTable.Where(x => !x.InActive).AsQueryable();

        if (codes!= null && codes.Any())
            query = query.Where(x => codes.Contains(x.FirstCode) || query.Contains(x.SecondCode));
        else
            query = query.Where(x => !x.HasException.HasValue);

        var data = query.ToList();
    }

I have tried it with WhereIF ienumerable but not succeed. Here is the link which I followed. https://extensionmethod.net/csharp/ienumerable-t/whereif


Solution

  • bool condition = codes!= null && codes.Any();
                var data  = _dBContext.QueryTable
                                           .WhereIf(condition, a=> codes.Contains(a.FirstCode) || codes.Contains(a.SecondCode))
                                           .WhereIf(!condition, a=> !a.HasException.HasValue && !a.InActive).ToList();