.NET Core EF Core(Entity Framework Core)去掉重復數據(distinct)


1、去重獲取單列數據的列表

1) 使用Distinct()方法

db.PageInfos.Select(p => p.Type).Distinct().ToList();

2)使用GroupBy()方法

db.PageInfos.GroupBy(p => p.Type).Select(p=>p.Key).ToList();

2、去重獲取Model數據的列表

使用DistinctBy()擴展方法來實現,可以返回Model列表數據。

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


免責聲明!

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



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