Ricibob
Ricibob

Reputation: 7705

LINQ to remove elements from one collection that don't match elements in another collection based on a field

I have 2 Lists of different objects eg List and List. I want to remove all objects in first list whos value of a field doesn't match on a value of a field in the second list.
Eg I want to remove all Type1 objects from the first list whos Type1.name (string) member doesnt match a Type2.id (string) member in the second list.
Is this possible with LINQ ?

Upvotes: 1

Views: 4725

Answers (2)

Mohamed Abed
Mohamed Abed

Reputation: 5113

You can also use lambda:

var query = (list1.Join(list2, x => x.Name, y => y.Id, (x, y) => x)).ToList();

or

var query = (Enumerable.Join(list1, list2, x => x.Name, y => y.Id, (x, y) => x)).ToList();

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500665

LINQ isn't about modifying existing collections - it's about running queries. If you need to change a list in place, you might want something like:

HashSet<string> ids = new HashSet<string>(list2.Select(x => x.Id));
list1.RemoveAll(x => !ids.Contains(x.Name));

In "normal" LINQ you could do this with:

// I'm assuming no duplicate IDs in list2 
var query = (from x in list1
             join y in list2 on x.Name equals y.Id
             select x).ToList();

Upvotes: 5

Related Questions