gpt4 book ai didi

c# - 什么时候应该使用 IEqualityComparer? C#

转载 作者:行者123 更新时间:2023-11-30 22:58:33 27 4
gpt4 key购买 nike

我有一个自定义对象列表,我试图在其中删除重复记录。我看到很多在线文章都指向 IEqualityComparer(我以前从未使用过它)。

问题是,我应该什么时候使用它?我可以通过 LINQ 在一行代码中实现相同的结果。

例子:

public static void Main(string[] args)
{
Product[] products =
{
new Product {Name = "apple", Code = 9},
new Product {Name = "orange", Code = 4},
new Product {Name = "apple", Code = 9},
new Product {Name = "lemon", Code = 12}
};

// Using Custom comparer
var usingCustomComparer = products.Distinct(new ProductComparer()).ToList();

// Using LINQ
var usinLinq = products.GroupBy(x => x.Name).Select(y => y.First()).ToList();
}

public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}

// Custom comparer for the Product class
private class ProductComparer : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{
if (ReferenceEquals(x, y)) return true;

if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) return false;

return x.Code == y.Code && x.Name == y.Name;
}

public int GetHashCode(Product product)
{
var hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();

var hashProductCode = product.Code.GetHashCode();

return hashProductName ^ hashProductCode;
}
}

两者的结果:

{Name = "apple", Code = 9},
{Name = "orange", Code = 4},
{Name = "lemon", Code = 12}

最佳答案

when should I use it?

一些可能性:

  • 当您对“平等”的定义比仅仅比较一个属性更复杂时
  • 当您想预定义“相等”以用于许多查询时
  • 当您想在 Linq 的外部定义“平等”时,例如当使用类作为哈希表的键时
  • 当您想在不重复代码的情况下稍微调整相等性的定义时(即打开/关闭区分大小写)

关于c# - 什么时候应该使用 IEqualityComparer? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52956178/

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