Distinct() with lambda?

前端 未结 18 963
南旧
南旧 2020-11-22 06:04

Right, so I have an enumerable and wish to get distinct values from it.

Using System.Linq, there\'s of course an extension method called Distinct<

18条回答
  •  旧巷少年郎
    2020-11-22 06:34

    Something I have used which worked well for me.

    /// 
    /// A class to wrap the IEqualityComparer interface into matching functions for simple implementation
    /// 
    /// The type of object to be compared
    public class MyIEqualityComparer : IEqualityComparer
    {
        /// 
        /// Create a new comparer based on the given Equals and GetHashCode methods
        /// 
        /// The method to compute equals of two T instances
        /// The method to compute a hashcode for a T instance
        public MyIEqualityComparer(Func equals, Func getHashCode)
        {
            if (equals == null)
                throw new ArgumentNullException("equals", "Equals parameter is required for all MyIEqualityComparer instances");
            EqualsMethod = equals;
            GetHashCodeMethod = getHashCode;
        }
        /// 
        /// Gets the method used to compute equals
        /// 
        public Func EqualsMethod { get; private set; }
        /// 
        /// Gets the method used to compute a hash code
        /// 
        public Func GetHashCodeMethod { get; private set; }
    
        bool IEqualityComparer.Equals(T x, T y)
        {
            return EqualsMethod(x, y);
        }
    
        int IEqualityComparer.GetHashCode(T obj)
        {
            if (GetHashCodeMethod == null)
                return obj.GetHashCode();
            return GetHashCodeMethod(obj);
        }
    }
    

提交回复
热议问题