Reputation: 3365
Which method of finding items in one collection based on a property value of each item in another collection is better? Over and above this, is there a better way to do this?
List<Thing> results;
List<Thing> thingList1 = ...;
List<Thing> thingList2 = ...;
Method A:
results = thingList1.Where(x => thingList2.Any(y => y.Id == x.Id)).ToList();
Method B:
foreach (Thing thing in thingList1)
{
results.AddRange(thingList2.Where(x => x.Id == thing.Id).Select(y => thing));
}
?
Upvotes: 1
Views: 70
Reputation: 53958
I would choose to make a join:
var results = (from item1 in thingList1
join item2 in thingList2
on item1.Id equals item2.Id
select item1).ToList();
I think the above approach is more clear in it's intention.
Another option, it would be to use the Intersect
method:
var results = thingList1.Intersect(thingList2);
This is more elegant. However, you should pay attention on implementing the interface IEquatable<Thing>
for your class Thing
. Otherwise, you can't use it. For further information, please have a look here.
Upvotes: 1
Reputation: 27944
The best way to know is writing a test with real data, however you are doing a where on a list multiple times. Making a Dictionary from the list will give you better performance.
Dictionary<int, thing> d = thingList2.ToDictornary(x => x.Id);
foreach (Thing thing in thingList1)
{
results.Add(d[thing.Id]);
}
Upvotes: 0