Avoid viewing the list several times using linq, with dynamic conditions (filter)

I have a list with objects Article. Parameters for this object:

Category, Description, Status, Class

The user can filter the list using the combination that he wants. Only description, or Category + Class, and so on.

So, if the user selects the criteria, I will get int> = 0, otherwise I will get -1.

For example, if he selects a filter with Statusand Category, I get

FilterCategory = x, FilterDescription = -1, FilterStatus = y, Filterclass = -1

My way to filter the list is as follows:

if (FilterCategory != -1)
    list = list.Where(a => a.Category == FilterCategory);
if (FilterDescription != -1)
    list = list.Where(a => a.Description == FilterDescription);
if (FilterStatus != -1)
    list = list.Where(a => a.Status == FilterStatus);
if (FilterClass != -1)
    list = list.Where(a => a.Class == FilterClass);

, 4 , . 4 . , != -1.

+3
3

, , Where, , :

if (FilterCategory != -1)
    list = list.Where(a => a.Category == FilterCategory);

:

list = list.Where(a => FilterCategory == -1 || a.Category == FilterCategory);

:

list = list.Where(a => (FilterCategory == -1 || a.Category == FilterCategory)
                    && (FilterDescription == -1 || a.Description == FilterDescription)
                    && (FilterStatus == -1 || a.Status == FilterStatus)
                    && (FilterClass == -1 || a.Class == FilterClass));

, .

+2

, Linq .Where . ToList/ToArray/First/Single/foreach .

+3
list = list.Where(a => (FilterCategory != -1 || a.Category == FilterCategory) && 
                                       (FilterDescription != -1 || a.Description == FilterDescription) &&
                                       (FilterStatus != -1 || a.Status == FilterStatus) &&
                                       (FilterClass != -1 || a.Class == FilterClass));
+1

Source: https://habr.com/ru/post/1726898/


All Articles