在網上看了LinQ有DistinctBy方法,實際在用的時候並沒有找到,后來參照了該網站才發現寫的是拓展方法
https://blog.csdn.net/c1113072394/article/details/75330966/
1.添加一個擴展方法
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;
}
}
}
使用方法如下(針對ID,和Name進行Distinct)
var query = people.DistinctBy(p => new { p.Id, p.Name });
3.若僅僅針對ID進行distinct:
var query = people.DistinctBy(p => p.Id);
————————————————
版權聲明:本文為CSDN博主「崔鈺璽」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/c1113072394/article/details/75330966/