I would like to know if this is possible to solve using a lambda expression:
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);
}
}
Sure you can! You can use this overload of Linq's Intersect
extension method which takes an IEqualityComparer<T>
, like this:
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();