LINQ: Distinct values

前端 未结 7 1299
一生所求
一生所求 2020-11-22 16:29

I have the following item set from an XML:

id           category

5            1
5            3
5            4
5            3
5            3
<
7条回答
  •  鱼传尺愫
    2020-11-22 16:57

    Since we are talking about having every element exactly once, a "set" makes more sense to me.

    Example with classes and IEqualityComparer implemented:

     public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
    
            public Product(int x, string y)
            {
                Id = x;
                Name = y;
            }
        }
    
        public class ProductCompare : IEqualityComparer
        {
            public bool Equals(Product x, Product y)
            {  //Check whether the compared objects reference the same data.
                if (Object.ReferenceEquals(x, y)) return true;
    
                //Check whether any of the compared objects is null.
                if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                    return false;
    
                //Check whether the products' properties are equal.
                return x.Id == y.Id && x.Name == y.Name;
            }
            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.Id.GetHashCode();
    
                //Calculate the hash code for the product.
                return hashProductName ^ hashProductCode;
            }
        }
    

    Now

    List originalList = new List {new Product(1, "ad"), new Product(1, "ad")};
    var setList = new HashSet(originalList, new ProductCompare()).ToList();
    

    setList will have unique elements

    I thought of this while dealing with .Except() which returns a set-difference

提交回复
热议问题