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

时间:2012-01-26 03:52:40

标签: 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();
    }
}

2 个答案:

答案 0 :(得分:4)

根据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;
}

答案 1 :(得分:1)

定义GetHashCode以返回唯一答案会导致Distinct按预期工作;

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;

}