首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >删除列表中的重复项(c#)

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

Stack Overflow用户
提问于 2012-01-26 11:52:40
回答 2查看 314关注 0票数 2

我想使用以下代码删除列表中的重复项,但它不起作用。有谁能开导我吗?谢谢。

代码语言:javascript
复制
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();
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-26 12:02:51

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

代码语言:javascript
复制
// 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;
}
票数 4
EN

Stack Overflow用户

发布于 2012-01-26 12:13:47

定义返回唯一答案的GetHashCode使Distinct按预期工作;

代码语言:javascript
复制
public int GetHashCode(Pairing obj)
{
     if (obj==null) return 0;
     var hc1 = obj.Index.GetHashCode();
     var hc2 = obj.Length.GetHashCode();
     var hc3 = obj.Offset.GetHashCode();

     return hc1 ^ hc2 ^ hc3;

}

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9013730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档