zoukankan      html  css  js  c++  java
  • C# 扩展方法——去重(Distinct)

    其他扩展方法详见:https://www.cnblogs.com/zhuanjiao/p/12060937.html

    IEnumerable的Distinct扩展方法,当集合元素为对象时,可用于元素对象指定字段进行排重集

    一、通过指定单个属性进行去重。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    namespace CoSubject.Common.CommonExtensions
    {
    	/// <summary>
    	/// IEnumerable的Distinct扩展方法
    	/// 当集合元素为对象时,可用于元素对象指定字段进行排重集
    	/// </summary>
    	public static class DistinctExtensions
    	{
    		public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector)
    		{
    			return source.Distinct(new CommonEqualityComparer<T, V>(keySelector));
    		}
    
    		public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source,  
                    Func<T, V> keySelector, IEqualityComparer<V> comparer)
    		{
    			return source.Distinct(new CommonEqualityComparer<T, V>(keySelector, comparer));
    		}
    	}
    
    	public class CommonEqualityComparer<T, V> : IEqualityComparer<T>
    	{
    		private Func<T, V> keySelector;
    		private IEqualityComparer<V> comparer;
    
    		public CommonEqualityComparer(Func<T, V> keySelector, IEqualityComparer<V> comparer)
    		{
    			this.keySelector = keySelector;
    			this.comparer = comparer;
    		}
    
    		public CommonEqualityComparer(Func<T, V> keySelector) : this(keySelector, EqualityComparer<V>.Default)
    		{ }
    
    		public bool Equals(T x, T y)
    		{
    			return comparer.Equals(keySelector(x), keySelector(y));
    		}
    
    		public int GetHashCode(T obj)
    		{
    			return comparer.GetHashCode(keySelector(obj));
    		}
    	}
    }
    

      

    举例:

    var member = memberAll.Distinct(d => d.MemberID); // 按照MemberID进行排重,不区分大小写

    var member = memberAll.Distinct(d => d.MemberID, StringComparer.CurrentCultureIgnoreCase);// 不区分大小写

    两个参数的扩展方法,第二个参数有以下几种可选。

    二、若是对多个属性去重如何实现呢?

    思路:主要是去实现IEqualityComparer<T> 泛型接口中的两个方法,Equals和GetHashCode,根据自己的需求去返回真假

    具体实现参照https://www.zhangshengrong.com/p/JKN8Eqo2X6/

    因为对象在比较的时候,会先调用GetHashCode方法,

    若HashCode不同 ,则对象不同,不会调用Equlas方法,

    若HashCode相同,再调用Equlas方法进行比较

    文章里面就是: 让GetHashCode方法返回常量,触发Equlas方法进行比较,Equlas里面写了自己所需要排重的属性进行判断

    三、排重是否有其他方式可以实现?

    有,memberAll.Where((m,i)=>memberAll.FindIndex(z=>z.MemberID== m.MemberID) == i) 

    另,GroupBy 可以实现

  • 相关阅读:
    不可或缺 Windows Native (15)
    不可或缺 Windows Native (14)
    不可或缺 Windows Native (13)
    不可或缺 Windows Native (12)
    不可或缺 Windows Native (11)
    不可或缺 Windows Native (10)
    不可或缺 Windows Native (9)
    不可或缺 Windows Native (8)
    不可或缺 Windows Native (7)
    不可或缺 Windows Native (6)
  • 原文地址:https://www.cnblogs.com/zhuanjiao/p/12082054.html
Copyright © 2011-2022 走看看