C# EF去除重復列DistinctBy


1.添加一個擴展方法

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

2.使用方法如下(針對ID,和Name進行Distinct)

var query = people.DistinctBy(p => new { p.Id, p.Name });

3.若僅僅針對ID進行distinct:

var query = people.DistinctBy(p => p.Id);


免責聲明!

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