Search code examples
c#linqremoveall

C# Linq RemoveAll with dynamic OR statement


I need to know if there is a way to create this part dynamically. Or, is it even possible? Using "Contians" will not work in this situation.

(x.Letter!= "a") && (x.Letter!= "b") && (x.Letter!= "e")

The "a", "b", "c" will be generated out of a ListBox using a for loop. There can be any number of items in the list box. That is why this must be dynamic.

MyList.RemoveAll(x => (x.Letter != "a") && (x.Letter!= "b") && (x.Letter!= "e"));

Solution

  • You do not need to make it dynamic, because the structure of your condition is very regular: you check containment against all items. Hence you can do it like this:

    var check = new List<string>(itemsFromListBox);
    MyList.RemoveAll(x => check.All(s => x.Letter != s));