Home > database >  Remove all elements in a IList that contains any of the other List's elements
Remove all elements in a IList that contains any of the other List's elements

Time:02-08

I have some strings in a IList as such:

IList - { "Apple", "Apple2" , Banana, Orange, "AppleBanana", Orange2, "Berries"};

I want to remove all of the elements that contains any elements from this list. List - {"apple", "orange", "grape"}

I am expecting the IList to be returned as - {Banana, "Berries"}

            Food food1 = new Food();
            Fruits fruit1 = new Fruits();
            fruit1.Name = "Apple";
            food1.fruits.Add(fruit1);
            Fruits fruit2 = new Fruits();
            fruit1.Name = "Apple2";
            food1.fruits.Add(fruit2);
            Fruits fruit3 = new Fruits();
            fruit1.Name = "Banana";
            food1.fruits.Add(fruit3);
            Fruits fruit4 = new Fruits();
            fruit1.Name = "AppleBanana";
            food1.fruits.Add(fruit4);
            Fruits fruit5 = new Fruits();
            fruit1.Name = "Orange";
            food1.fruits.Add(fruit5);
            Fruits fruit6 = new Fruits();
            fruit1.Name = "Orange2";
            food1.fruits.Add(fruit6);
            Fruits fruit7 = new Fruits();
            fruit1.Name = "Berries";
            food1.fruits.Add(fruit7);
        }
        public class Food
        {
            public IList<Fruits> fruits;

            public Food()
            {
                fruits = new List<Fruits>();
            }
        }

        public class Fruits
        {
            public string Name;
        }

CodePudding user response:

list1.Where(f=>list2.Contains(f)).ToList();

CodePudding user response:

try this

var food = new Food(new string[] { "Apple", "Apple2", " Banana", "Orange", "AppleBanana", "Orange", "Berries" });

var fruitsToRemove = new String[] { "apple", "orange", "grape" };

food.Fruits = food.Fruits.Where(i => !fruitsToRemove.Contains(i.Name.ToLower())).ToList();

classes

public class Food
{
    public List<Fruit> Fruits {get;set;} =new List<Fruit>();

    public Food(IEnumerable<string> fruits)
    {
        Fruits = fruits.Select(f => new Fruit {Name=f}).ToList();
    }
}

public class Fruit
{
    public string Name;
}
  •  Tags:  
  • Related