Search code examples
c#linqlambda

Linq where clause based on different bool condition C#


Hi i'm trying to filter a list of items based on multiple bool parameters. I have 3 bool parameters (they are 3 checkbox in the UI): IsTypeA, IsTypeB, IsTypeC. Based on this 3 values i have to filter my list on a enum property of the items (called simply "Type"). Multiple checkbox can be checked. There's also another filter ("in", "out") above the type filter, but that is working. What i've tried so far is this:

FilteredDashboardItems = AllItems?.Where(x => 
                    Destination == "in" ?
                    (
                        (IsTypeA == true ? x.Type == Helpers.Enum.A : true)                    
                        &&
                        (IsTypeB == true ? x.Type == Helpers.Enum.B : true)                    
                        &&
                        (IsTypeC == true ? x.Type == Helpers.Enum.C : true)                    
                    ) : 
                    Destination == "out" ?
                    (
                        (IsTypeA == true ? x.Type == Helpers.Enum.A : true)                    
                        &&
                        (IsTypeB == true ? x.Type == Helpers.Enum.B : true)                    
                        &&
                        (IsTypeC == true ? x.Type == Helpers.Enum.C : true)                    
                    ) : true)?.ToList();

Problem is: if i singularly check a checkbox (let's say IsTypeA), the list gets correctly filtered for A Type items. But if i check another checkbox (let's say IsTypeB) instead of showing me A + B types filtered list, the list returns 0 items. How can i solve that?


Solution

  • You would need something like this:

        List<int> typesToCheck = new List<int>();
    
        if (IsTypeA) typesToCheck.Add((int)Helpers.A);
        if (IsTypeB) typesToCheck.Add((int)Helpers.B);
        if (IsTypeC) typesToCheck.Add((int)Helpers.C);
    
        FilteredDashboardItems = AllItems?.Where(x => Destination == "in" ?
            (IsTypeA || IsTypeB || IsTypeC ? typesToCheck.Contains(x.Type) : true)
            :
            Destination == "out" ?
                (IsTypeA || IsTypeB || IsTypeC ? typesToCheck.Contains(x.Type) : true)
                : 
                true)?.ToList();
    

    And once you get it to this form, I'm sure you can also simplify the Destination conditions