你可以试试:
var result = listOne.Join(listTwo,
(one) => one,
(two) => two,
(one, two) => one,
new MyFooComparer());
哪里MyFooComparer
可能看起来像:
class MyFooComparer : IEqualityComparer<Foo>
{
public bool Equals(Foo x, Foo y)
{
return x.Id == y.Id && x.someKey != y.someKey;
}
public int GetHashCode(Foo obj)
{
return obj.Id.GetHashCode();
}
}
[更新]
Intersect
我对vs.的性能很好奇,Join
所以我在我的解决方案和 @pswg 的解决方案之间做了一个小的性能比较(每个listOne
有listTwo
10 个项目):
var comparer = new MyFooComparer();
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 100000; i++)
{
var result1 = listOne.Intersect(listTwo, comparer).ToList();
}
Console.WriteLine("Intersect: {0}",sw.Elapsed);
sw.Restart();
for (int i = 0; i < 100000; i++)
{
var result = listOne.Join(listTwo,
(one) => one,
(two) => two,
(one, two) => one,
comparer);
}
Console.WriteLine("Join: {0}", sw.Elapsed);
输出:
Intersect: 00:00:00.1441810
Join: 00:00:00.0037063