我正在尝试使用“Union”合并两个列表,以便消除重复项。以下是示例代码:
现在的问题是,我能否使用Union并且仍然获取具有最新日期(使用SomeDate属性)的记录。该记录可以位于tempList1或tempList2中。
提前感谢。
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();
现在的问题是,我能否使用Union并且仍然获取具有最新日期(使用SomeDate属性)的记录。该记录可以位于tempList1或tempList2中。
提前感谢。
(item1, item2) => (item1.SomeDate > item2.SomeDate) ? item1 : item2)
.ToList(); - Ganesha
x.SomeValue1 == y.SomeValue1 && x.SomeValue2 == y.SomeValue2
来比较项目的。这意味着你想要选择一组 SomeValue1 和 SomeValue2 作为键。(在 C# 中,最好的选项可能是使用匿名类型。我会更新我的答案并提供代码。) - Noldorin