其他擴展方法詳見: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 可以實現
