通過自定義擴展方法DistinctBy實現去重


C#代碼如下

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;
        }
    }
}

使用方法

1、針對ID,和Name進行Distinct
var query = allProduct.DistinctBy(p => new { p.Id, p.Name });
2、僅僅針對ID進行distinct:
var query = allProduct.DistinctBy(p => p.Id);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM