哪个更高效/优雅?

Which is more efficient / elegant?

根据另一个集合中每个项目的属性值在一个集合中查找项目的哪种方法更好?除此之外,还有更好的方法吗?

List<Thing> results;    

List<Thing> thingList1 = ...;
List<Thing> thingList2 = ...;

方法一:

results = thingList1.Where(x => thingList2.Any(y => y.Id == x.Id)).ToList();

方法 B:

foreach (Thing thing in thingList1)
{
    results.AddRange(thingList2.Where(x => x.Id == thing.Id).Select(y => thing));
}      

我会选择加入:

var results = (from item1 in thingList1
               join item2 in thingList2
               on item1.Id equals item2.Id
               select item1).ToList();

我觉得上面的做法用意比较明确。

另一个选择,就是使用Intersect方法:

var results = thingList1.Intersect(thingList2);

这样比较优雅。但是,您应该注意为您的 class Thing 实现接口 IEquatable<Thing>。否则,你不能使用它。更多信息,请查看here.

最好的了解方法是使用真实数据编写测试,但是您要多次执行列表中的某个位置。从列表中创建字典会给你更好的性能。

Dictionary<int, thing> d = thingList2.ToDictornary(x => x.Id);
foreach (Thing thing in thingList1)
{
    results.Add(d[thing.Id]);
}