Search code examples
c#sqllinqlinq-to-sqlentity-framework-4

Avoid Lambda expression with multiple where clause


How can we define multiple where clause in a single lambda expression. What I need, if lambda expression finds result with matching criteria then it filters out only those records otherwise it will return all records. I want to get this in a single lambda expression. As I have multiple criteria on which I have to filter records from database using lambda expression.

I don't want to use if else conditions and then change my lambda expression accordingly. I want to achieve this in a single expression.

var objList = from o in db.sometable
                              join p in db.sometable1 on o.sometable1Id equals p.Id
                              join q in db.sometable2 on p.Id equals q.Id
                              join r in db.sometable3 on p.Id equals r.Id
                              join s in db.sometable4 on o.id equals s.Id
                              where r.1stcriteria == X || r.2ndCriteria == Y || r.3rdCriteria == Z
                              select new
                              {
                                  o.Id,
                                  r.X,
                                  r.Y,
                                  s.Name,
                                  o.area_sold,
                                  p.stock

                              };

On above expression i need to get result even if no criteria match or any one of them matched.Or even two of them matched.


Solution

  • I don't fully understand, you can use multible criteria on where: list.where(x=> (condition1) || (condition2)). To get the whole list simply add one if afterwards:

    var filteredList = myList.where(x=> (conditions1(x)) || (condition2(x))).toList();
    
    if (filteredList.count == 0)
        filteredList = myList;