C#Linq-如何从集合中获取不同的集合 [英] C# Linq- How to get distinct collection from a collection

查看:477
本文介绍了C#Linq-如何从集合中获取不同的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下收藏:

public IList<Emp> EmpList()
{
    IList<Emp> empList = new List<Emp>();
    empList.Add(new Emp() { Id = 1, Name = "abc1" });
    empList.Add(new Emp() { Id = 1, Name = "abc2" });        
    empList.Add(new Emp() { Id = 2, Name = "abc3" });
    empList.Add(new Emp() { Id = 2, Name = "abc4" });
    empList.Add(new Emp() { Id = 4, Name = "abc5" });
    return empList;
}

我想基于EmpList()集合中的ID获得不同的记录.我的意思是EmpList()集合的第一行,第三行和最后一行.

I wants to get distinct records based on Id from the EmpList() collection. I mean first row, third row and last row from the EmpList() collection.

任何帮助将不胜感激.

编辑-var empList = emp.EmpList().GroupBy(x => x.Id).Select(x => x.First()); 该查询对于该解决方案工作正常.

Edit-var empList = emp.EmpList().GroupBy(x => x.Id).Select(x => x.First()); This query is working fine for the solution.

推荐答案

您可以在 MoreLINQ 中使用它

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

并像这样使用它:

return empList.DistinctBy(x => x.Id).ToList();

这篇关于C#Linq-如何从集合中获取不同的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆