Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove All from List where each line doesn't contain any item from another list

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)));
like image 292
Kulingar Avatar asked Mar 23 '23 01:03

Kulingar


1 Answers

I personally like using .Any(), it seems more fitting to me;

    products.RemoveAll(p => !fruits.Any(f => f.IndexOf(p, StringComparison.CurrentCultureIgnoreCase) >= 0));
like image 157
Az Za Avatar answered Apr 16 '23 14:04

Az Za