Search code examples
c#linqasp.net-core-2.2

How to dynamically add or remove where clause in LINQ


Here is my LINQ query that needs to update to dynamic where clause. If parameter's id value is 0 then where clause should return all records else where clause should match records as per id value.

public async Task<IEnumerable<dynamic>> GetFilteredRowsByID(int id)
        {
            return from m in _context.TableName
                   where m.id == (id != 0 ? id : /*AllRecordsHere*/ )
                   join ...
                   join ...
                   select new {...}
        }

I use Asp.Net Core 2.2. Is it possible without writing another method witout where clause for this?


Solution

  • Try condition:

    where id == 0 || m.id == id
    

    in case when id == 0, whole expression evaluates to true, otherwise it is false and second condition m.id == id would be checked.