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

本文关键字:删除列 列表 删除 | 更新日期: 2023-09-27 18:21:22

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

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

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

根据IEnumerable.Dispinct页面上的示例,您需要实现GetHashCode(),以便相等的对象返回相同的哈希代码。如果不重写对象中的GetHashCode(),则不能保证返回相同的哈希代码。

// 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;
}

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

}