C# EF去除重复列DistinctBy

1.添加一个扩展方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);  
转 https://www.cnblogs.com/hsjloveit/p/12509818.html
posted @   dreamw  阅读(470)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
历史上的今天:
2021-07-08 使用gitlab自带的ci/cd实现.net core应用程序的部署
2021-07-08 详解C++中的多态和虚函数
点击右上角即可分享
微信分享提示