Joh*_*han 11 c# linq asp.net lambda set-intersection
我想知道使用lambda表达式是否可以解决这个问题:
List<Foo> listOne = service.GetListOne();
List<Foo> listTwo = service.GetListTwo();
List<Foo> result = new List<Foo>();
foreach(var one in listOne)
{
foreach(var two in listTwo)
{
if((one.Id == two.Id) && one.someKey != two.someKey)
result.Add(one);
}
}
Run Code Online (Sandbox Code Playgroud)
p.s*_*w.g 12
你当然可以!您可以使用Linq的扩展方法的这个重载,Intersect它采用IEqualityComparer<T>如下:
public class FooComparer : IEqualityComparer<Foo>
{
public bool Equals(Foo x, Foo y)
{
return x.Id == y.Id && x.someKey != y.someKey;
}
public int GetHashCode(Foo x)
{
return x.Id.GetHashCode();
}
}
...
var comparer = new FooComparer();
List<Foo> listOne = service.GetListOne();
List<Foo> listTwo = service.GetListTwo();
List<Foo> result = listOne.Intersect(listTwo, comparer).ToList();
Run Code Online (Sandbox Code Playgroud)
listOne.SelectMany(x=>listTwo.Where(y=>x.Id==y.Id && x.someKey != y.someKey));
Run Code Online (Sandbox Code Playgroud)