C# EF去除重复列DistinctBy

在网上看了LinQ有DistinctBy方法,实际在用的时候并没有找到,后来参照了该网站才发现写的是拓展方法

https://blog.csdn.net/c1113072394/article/details/75330966/ 

1.添加一个扩展方法

    public static class DistinctByClass
    {
        public static IEnumerable DistinctBy(this IEnumerable source, Func keySelector)
        {
            HashSet seenKeys = new HashSet();
            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);

 

你可能感兴趣的:(C#,C#,distinct)