Distinct() with lambda?

前端 未结 18 1153
南旧
南旧 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:35

    No there is no such extension method overload for this. I've found this frustrating myself in the past and as such I usually write a helper class to deal with this problem. The goal is to convert a Func to IEqualityComparer.

    Example

    public class EqualityFactory {
      private sealed class Impl : IEqualityComparer {
        private Func m_del;
        private IEqualityComparer m_comp;
        public Impl(Func del) { 
          m_del = del;
          m_comp = EqualityComparer.Default;
        }
        public bool Equals(T left, T right) {
          return m_del(left, right);
        } 
        public int GetHashCode(T value) {
          return m_comp.GetHashCode(value);
        }
      }
      public static IEqualityComparer Create(Func del) {
        return new Impl(del);
      }
    }
    

    This allows you to write the following

    var distinctValues = myCustomerList
      .Distinct(EqualityFactory.Create((c1, c2) => c1.CustomerId == c2.CustomerId));
    

提交回复
热议问题