Karthi
Karthi

Reputation: 585

How to remove list element?

I have two lists like below.

List<string> apple= new List<string>();
  apple.Add("a");
  apple.Add("b");

List<string> ball= new List<string>();
  ball.Add("a,b");
  ball.Add("b,c");
  ball.Add("c,a");

Now I want to remove elements from the ball list that of which there are substrings of those elements in the apple list. That is if "a" occurs in ball list element, I have to remove those listelements from the ball list.

My expected output of ball list should be (b,c).

Upvotes: 1

Views: 56

Answers (2)

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35780

You can try this:

ball = ball.Where(b => !apple.Any(a => b.Contains(a))).ToList();

Upvotes: 1

Andrei Tătar
Andrei Tătar

Reputation: 8295

Here a quick LinqPad

var apple= new List<string>();
apple.Add("a");

var ball= new List<string>();
ball.Add("a,b");
ball.Add("b,c");
ball.Add("c,a");

ball.Where(b=>apple.Any(b.Contains))
    .ToList() //create a duplicate, also lists have ForEach
    .ForEach(b=>ball.Remove(b));

ball.Dump();

Output is:

b,c

Upvotes: 2

Related Questions