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; } } }
使用方法如下(针对ID,和Name进行Distinct)
var query = people.DistinctBy(p => new { p.Id, p.Name });
若仅仅针对ID进行distinct:
var query = people.DistinctBy(p => p.Id);
调用上面的那个方法是,方法所在的类要是静态类
————————————————
版权声明:本文为CSDN博主「崔钰玺」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/c1113072394/java/article/details/75330966