Distinct() with lambda?

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

    You can use InlineComparer

    public class InlineComparer : IEqualityComparer
    {
        //private readonly Func equalsMethod;
        //private readonly Func getHashCodeMethod;
        public Func EqualsMethod { get; private set; }
        public Func GetHashCodeMethod { get; private set; }
    
        public InlineComparer(Func equals, Func hashCode)
        {
            if (equals == null) throw new ArgumentNullException("equals", "Equals parameter is required for all InlineComparer instances");
            EqualsMethod = equals;
            GetHashCodeMethod = hashCode;
        }
    
        public bool Equals(T x, T y)
        {
            return EqualsMethod(x, y);
        }
    
        public int GetHashCode(T obj)
        {
            if (GetHashCodeMethod == null) return obj.GetHashCode();
            return GetHashCodeMethod(obj);
        }
    }
    

    Usage sample:

      var comparer = new InlineComparer((i1, i2) => i1.PeticionEV == i2.PeticionEV && i1.Etiqueta == i2.Etiqueta, i => i.PeticionEV.GetHashCode() + i.Etiqueta.GetHashCode());
      var peticionesEV = listaLogs.Distinct(comparer).ToList();
      Assert.IsNotNull(peticionesEV);
      Assert.AreNotEqual(0, peticionesEV.Count);
    

    Source: https://stackoverflow.com/a/5969691/206730
    Using IEqualityComparer for Union
    Can I specify my explicit type comparator inline?

提交回复
热议问题