c# - 删除列表中的重复项 (c#)

标签 c#

我想使用以下代码删除列表中的重复项,但它不起作用。有人可以启发我吗?谢谢。

public sealed class Pairing
{
    public int Index { get; private set; }
    public int Length { get; private set; }
    public int Offset { get; private set; }

    public Pairing(int index, int length, int offset)
    {
        Index = index;
        Length = length;
        Offset = offset;
    }
}


class MyComparer : IEqualityComparer<Pairing>
{
    public bool Equals(Pairing x, Pairing y)
    {
        return ((x.Index == y.Index) && (x.Length == y.Length) && (x.Offset == y.Offset));
    }

    public int GetHashCode(Pairing obj)
    {
        return obj.GetHashCode();
    }
}
class Program
{
    static void Main(string[] args)
    {
        List<Pairing> ps = new List<Pairing>();
        ps.Add(new Pairing(2, 4, 14));
        ps.Add(new Pairing(1, 2, 4));
        ps.Add(new Pairing(2, 4, 14));

        var unique = ps.Distinct(new MyComparer());
        foreach (Pairing p in unique)
        {
            Console.WriteLine("{0}\t{1}\t{2}", p.Index, p.Length, p.Offset);
        }
        Console.ReadLine();
    }
}

最佳答案

根据IEnumerable.Distinct上的示例在页面中,您需要实现 GetHashCode() 以便相等的对象返回相同的哈希码。如果您没有覆盖对象中的 GetHashCode() ,则它是 not guaranteed to return the same hashcode

// If Equals() returns true for a pair of objects 
// then GetHashCode() must return the same value for these objects.

public int GetHashCode(Product product)
{
    //Check whether the object is null
    if (Object.ReferenceEquals(product, null)) return 0;

    //Get hash code for the Name field if it is not null.
    int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();

    //Get hash code for the Code field.
    int hashProductCode = product.Code.GetHashCode();

    //Calculate the hash code for the product.
    return hashProductName ^ hashProductCode;
}

关于c# - 删除列表中的重复项 (c#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9013730/

相关文章:

c# - 我应该在哪里创建 MVP 中的数据投影? Presenter 还好吗?

c# - 正则表达式替换字符串

c# - SignalR C# 客户端 407 需要代理身份验证

c# - 在为 datagridview 分配数据源时添加行

C# 结构默认值

c# - 对不一致的行结尾说"is"?

c# - Windows窗体应用程序-文本突出显示

c# - Office 365 REST API

c# - 如何在不使用 try catch 的情况下处理异常?

c# - 使用从通用方法获取的参数调用方法