I’m trying to merge 2 lists using “Union” so I get rid of duplicates. Following is the sample code:
public class SomeDetail
{
public string SomeValue1 { get; set; }
public string SomeValue2 { get; set; }
public string SomeDate { get; set; }
}
public class SomeDetailComparer : IEqualityComparer<SomeDetail>
{
bool IEqualityComparer<SomeDetail>.Equals(SomeDetail x, SomeDetail y)
{
// Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y))
return true;
// Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x.SomeValue1 == y.SomeValue1 && x.SomeValue2 == y.SomeValue2;
}
int IEqualityComparer<SomeDetail>.GetHashCode(SomeDetail obj)
{
return obj.SomeValue1.GetHashCode();
}
}
List<SomeDetail> tempList1 = new List<SomeDetail>();
List<SomeDetail> tempList2 = new List<SomeDetail>();
List<SomeDetail> detailList = tempList1.Union(tempList2, SomeDetailComparer).ToList();
Now the question is can I use Union and still get the record which has the latest date (using SomeDate property). The record itself can either be in tempList1 or tempList2.
Thanks in advance
The operation that is really suited to this purpose is an full outer join. The
Enumerableclass has an implementation of inner join, which you can use to find the duplicates and select whichever you prefer.keySelectoris simply a function (could be a lambda expression) that extracts a key from an object of typeSomeDetail. Now, to implement the full outer join, try something like this:equalityComparershould be an object that implementsIEqualityComparer<SomeDetail>and effectively uses thekeyComparerfunction for testing equality.Let me know if that does the job for you.