2012-01-26 329 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; 

}