gpt4 book ai didi

C# 泛型列表联合问题

转载 作者:太空狗 更新时间:2023-10-29 18:28:28 24 4
gpt4 key购买 nike

我正在尝试使用“Union”合并 2 个列表,以便删除重复项。以下是示例代码:

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 中。

提前致谢

最佳答案

真正适合这个目的的操作是 full outer join . Enumerable类具有内部联接的实现,您可以使用它来查找重复项并选择您喜欢的任何一个。

var duplicates = Enumerable.Join(tempList1, tempList2,  keySelector, keySelector, 
(item1, item2) => (item1.SomeDate > item2.SomeDate) ? item1 : item2)
.ToList();

keySelector只是一个从 SomeDetail 类型的对象中提取键的函数(可以是 lambda 表达式) .现在,要实现完整的外部连接,请尝试这样的事情:

var keyComparer = (SomeDetail item) => new { Value1 = item.SomeValue1,
Value2 = item.SomeDetail2 };
var detailList = Enumerable.Union(tempList1.Except(tempList2, equalityComparer),
tempList2.Except(tempList1, equalityComparer)).Union(
Enumerable.Join(tempList1, tempList2, keyComparer, keyComparer
(item1, item2) => (item1.SomeDate > item2.SomeDate) ? item1 : item2))
.ToList();

equalityComparer应该是一个实现 IEqualityComparer<SomeDetail> 的对象并有效地使用 keyComparer用于测试相等性的函数。

让我知道这是否适合您。

关于C# 泛型列表联合问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/849545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com