System.Linq Distinct 方法使用

  • 首先看到Distinct 肯定会想当然的直接.Distinct() 这样调用。
  • 需要知道这里的Distinct 是以对象为单位来去重的。当你Select new 映射的时候就算属性值相同也不会进行去重。
  • 单列的使用这里就略过使用了 
  • 多列的使用(比如我需要去重KeyValuePairModel 这个对象 ):
     public class KeyValuePairModel
        {
            public string Name { get; set; }
            public string Code { get; set; }
        }
    // 这里底层会先判断比较的对象是否是同一个对象 首先会调用GetHashCode 如果不是同一对象才会调用Equals方法。
        public class KeyValuePairRowComparer : IEqualityComparer<KeyValuePairModel>
        {
            public bool Equals(KeyValuePairModel t1, KeyValuePairModel t2)
            {
                return (t1.Name == t2.Name && t1.Code == t2.Code);
            }
            public int GetHashCode(KeyValuePairModel t)
            {
                return t.ToString().GetHashCode();
            }
        }
  • 使用:
    arealist.Select(c => new KeyValuePairModel() { Code = c.CityCode, Name = c.CityName }).Distinct(new KeyValuePairRowComparer())

猜你喜欢

转载自www.cnblogs.com/chongyao/p/12357899.html