LINQ to remove elements from one collection that don't match elements in another collection based on a field
I have 2 L开发者_如何学Cists 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 ?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();
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();
精彩评论