gpt4 book ai didi

c# - 在 List<[linq_custom_object]>() 上实现 .Distinct() 的正确方法是什么?

转载 作者:太空狗 更新时间:2023-10-30 00:31:49 25 4
gpt4 key购买 nike

我有这门课DNS_Log有四个属性。我已经创建了这些对象的列表,我试图过滤这些对象,但仅针对不同的事件。 (在填充列表时,有很多重复)

这是正在填充的列表:

dnsLogs.Add( new DNS_Log { Destination = destination, 
Source_IP = sourceIp,
Domain_Controller = domainController,
DateTime = datetime });

这是我试图过滤掉不同的尝试:

dnsLogs = dnsLogs.Distinct().ToList();

为什么这不起作用?我需要在 distinct 参数中使用一些 linq 表达式吗?我想比较整个对象的属性。有更简单的方法吗?

附言我玩过定制 IEqualityComparer<DNS_Log>这似乎工作正常,但我不知道如何在这种情况下实现它。

最佳答案

您有多种选择:

  1. 实现 IEquatable<T>在类型上 DNS_Log
  2. 在不实现 IEquatable<T> 的情况下覆盖 Equals 和 GetHashCode
  3. 实现一个单独的 IEqualityComparer<T>并将其传递给 Distinct

注意!在下面的所有代码中,相等性检查假定 ==运算符(operator)知道如何处理每种类型。对于 DateTime 成员来说确实如此(假设它也是类型的 DateTime),但我显然不能保证其他成员也能正常工作。如果 Destination 成员拥有 == 的类型operator 没有被定义,这很可能会做错事。由于您还没有为这个比较器实现发布自己的代码,所以不可能知道在这里做什么。

IEquatable<T>

public class DNS_Log : IEquatable<DNS_Log>
{

public bool Equals(DNS_Log other)
{
if (other == null)
return false;

return (other.Destination == Destination
&& other.Source_IP == Source_IP
&& other.Domain_Controller == Domain_Controller
&& other.DateTime == DateTime);
}

public override int GetHashCode()
{
int hash = 23;
hash = hash * 59 + (Destination == null ? 0 : Destination.GetHashCode());
hash = hash * 59 + (Source_IP == null ? 0 : Source_IP.GetHashCode());
hash = hash * 59 + (Domain_Controller == null ? 0 : Domain_Controller.GetHashCode());
hash = hash * 59 + DateTime.GetHashCode();
return hash;
}
}

在没有接口(interface)的情况下覆盖 Equals 和 GetHashCode

public class DNS_Log
{

public override bool Equals(object obj)
{
if (obj == null) return false;
var other = obj as DNS_Log;
if (other == null) return false;

... rest the same as above

分开IEqualityComparer<T>

最后,您可以提供 IEqualityComparer<T>打电话时 Distinct :

dnsLogs = dnsLogs.Distinct(new DNS_LogEqualityComparer()).ToList();

public class DNS_LogEqualityComparer : IEqualityComparer<DNS_Log>
{
public int GetHashCode(DNS_Log obj)
{
int hash = 23;
hash = hash * 59 + (obj.Destination == null ? 0 : obj.Destination.GetHashCode());
hash = hash * 59 + (obj.Source_IP == null ? 0 : obj.Source_IP.GetHashCode());
hash = hash * 59 + (obj.Domain_Controller == null ? 0 : obj.Domain_Controller.GetHashCode());
hash = hash * 59 + obj.DateTime.GetHashCode();
return hash;
}

public bool Equals(DNS_Log x, DNS_Log y)
{
if (ReferenceEquals(x, y)) return true;
if (x == null) return false;

return (x.Destination == y.Destination
&& x.Source_IP == y.Source_IP
&& .Domain_Controller == y.Domain_Controller
&& x.DateTime == y.DateTime);
}
}

关于c# - 在 List<[linq_custom_object]>() 上实现 .Distinct() 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22381779/

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