C# 撰寫擴展CLASS - DistinctBy
C# 撰寫擴展CLASS - DistinctBy
void Main()
{
List<ClassA> list = new List<UserQuery.ClassA>();
list.Add(new ClassA() { strA = "A", strB = "A1" });
list.Add(new ClassA() { strA = "B", strB = "B1" });
list.Add(new ClassA() { strA = "B", strB = "C1" });
var a = list.DistinctBy(x => x.strA).ToList();
// strA , strB
// A, A1
// B, B1
var b = list.DistinctBy(x => x.strB).ToList();
// strA , strB
// A, A1
// B, B1
// B, C1
}
public class ClassA
{
public string strA {get;set;}
public string strB {get;set;}
}
//撰寫一個擴展CLASS
public static class DistinctByClass
{
//方法套用在列舉上
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
}
DistinctBy可以直接使用在 list 上, 是因為 DistinctByClass 是一個靜態的擴展CLASS, 由方法DinstinctBy來看, 可以接受 IEnumerable< TSource > 。
留言
張貼留言