How to use the IEqualityComparer

前端 未结 6 1899
一向
一向 2020-11-27 04:36

I have some bells in my database with the same number. I want to get all of them without duplication. I created a compare class to do this work, but the execution of the fun

6条回答
  •  醉话见心
    2020-11-27 04:55

    Just code, with implementation of GetHashCode and NULL validation:

    public class Class_reglementComparer : IEqualityComparer
    {
        public bool Equals(Class_reglement x, Class_reglement y)
        {
            if (x is null || y is null))
                return false;
    
            return x.Numf == y.Numf;
        }
    
        public int GetHashCode(Class_reglement product)
        {
            //Check whether the object is null 
            if (product is null) return 0;
    
            //Get hash code for the Numf field if it is not null. 
            int hashNumf = product.hashNumf == null ? 0 : product.hashNumf.GetHashCode();
    
            return hashNumf;
        }
    }
    

    Example: list of Class_reglement distinct by Numf

    List items = items.Distinct(new Class_reglementComparer());
    

提交回复
热议问题