I have 6 values ​​for which you need to filter data:

  1. date c / f
  2. s / f number
  3. provider
  4. recipient
  5. executor
  6. Tin company

enter image description here

On the server side, I get a string [] with these values. If the cap is above the field, the parameter participates in filtering and vice versa. How to form a LINQ query that, if there is no parameter in string [], does not consider it in data filtering and vice versa.

var MySelect = from q in MyDB ...??? 
  • A little off topic, but I can not pass by. "Invoice" in the plural is written as "invoice" , not "invoice invoice" :) - Pavel Mayorov
  • Great remark! But, nevertheless, LINQ request interests me more. - ArtemiyMVC February
  • And about the request, I already answered you. - Pavel Mayorov

1 answer 1

Like that:

 var q = from row in ... ... select row; // Базовый запрос без фильтров if (фильтр 1 установлен) q = q.Where(row => условие фильтра 1); if (фильтр 2 установлен) q = q.Where(row => условие фильтра 2); if (фильтр 3 установлен) q = q.Where(row => условие фильтра 3); if (фильтр 4 установлен) q = q.Where(row => условие фильтра 4); if (фильтр 5 установлен) q = q.Where(row => условие фильтра 5); if (фильтр 6 установлен) q = q.Where(row => условие фильтра 6); if (фильтр 7 установлен) q = q.Where(row => условие фильтра 7); 
  • Do I understand correctly that a basic query without filters will load the entire database, and then Where will be performed on the collection loaded into memory? - Alexcei Shmakov
  • 2
    No, wrong. As long as the type of the expression remains IQueryable<...> - nothing will really happen, only the query expression will accumulate. - Pavel Mayorov
  • That's when you call, for example, ToList - then the query will go to the database. With all the accumulated conditions. - Pavel Mayorov
  • And if I choose a filter 1,2,6? Your scheme involves the listing of all query options. In my opinion this is factorial. Factorial from 6 = 720. Total 720 queries! Correct if not right. - ArtemiyMVC February
  • one
    @ArtemiyMVC expanded the answer to 7 filters, since you are so afraid of this number. - Pavel Mayorov