How to use the IEqualityComparer

前端 未结 6 1901
一向
一向 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 05:16

    If you want a generic solution without boxing:

    public class KeyBasedEqualityComparer : IEqualityComparer
    {
        private readonly Func _keyGetter;
    
        public KeyBasedEqualityComparer(Func keyGetter)
        {
            _keyGetter = keyGetter;
        }
    
        public bool Equals(T x, T y)
        {
            return EqualityComparer.Default.Equals(_keyGetter(x), _keyGetter(y));
        }
    
        public int GetHashCode(T obj)
        {
            TKey key = _keyGetter(obj);
    
            return key == null ? 0 : key.GetHashCode();
        }
    }
    
    public static class KeyBasedEqualityComparer
    {
        public static KeyBasedEqualityComparer Create(Func keyGetter)
        {
            return new KeyBasedEqualityComparer(keyGetter);
        }
    }
    

    usage:

    KeyBasedEqualityComparer.Create(x => x.Numf)
    

提交回复
热议问题