For what it's worth, I spent a while looking at the below post which is relevant except that it's working on the same list with several properties instead of two independent lists, nor does it involve a text contain comparison as opposed to an item match.
How to remove all objects from List<object> where object.variable exists at least once in any other object.variable2?
I have a String List full of fruit called 'fruits'
Apple
Orange
Banana
I also have a String List called products which is full of some fruits (plus other misc information) and some other products as well.
ShoeFromNike
ApplePie
OrangeDrink
I need to remove all items from the second list where each individual line doesn't string contain ANY of the items listed in the Fruit List.
The end result would be the products list containing only:
ApplePie
OrangeDrink
My best iterating approach:
//this fails becaucse as I remove items the indexes change and I remove the wrong items (I do realize I could reverse this logic and if it meets the criteria ADD it to a new list and i'm sure there's a better way.)
for (int i = 0; i < products.Count(); i++)
{
bool foundMatch = false;
foreach (string fruit in fruits)
if (products[i].Contains(fruit))
foundMatch = true;
if (foundMatch == false)
products.Remove(products[i]);
}
My best lambda approach:
products.RemoveAll(p => !p.Contains(fruits.Select(f=> f)));
I personally like using .Any(), it seems more fitting to me;
products.RemoveAll(p => !fruits.Any(f => f.IndexOf(p, StringComparison.CurrentCultureIgnoreCase) >= 0));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With