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删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM