2012-01-26 334 views
2

我想使用下面的代码删除列表中的重复项,但它不起作用。任何人都可以启发我吗?谢谢。删除列表中的重复项(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(); 
    } 
} 

回答

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

定义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; 

}