简体   繁体   中英

Which is more efficient / elegant?

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));
}      

?

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 .

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]);
}     

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM