C# EF去除重復列DistinctBy


在網上看了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/


免責聲明!

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



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