简体   繁体   English

使用LINQ和C#从分组列表中获取MAX 5项

[英]Get MAX 5 items from a grouped List with LINQ and C#

I have a grouped List of items, grouped by the name. 我有一个分组的项目清单,按名称分组。

So for example I have item[0] that has 4 items, item[1] that has 6 items, item [2] that has 10 items etc. 因此,例如,我有具有4个项目的item [0],具有6个项目的item [1],具有10个项目的item [2]等。

Now I want to get Max 5 items, ie those that have the most items inside this GroupedList. 现在,我想获取最多5个项目,即该GroupedList中具有最多项目的项目。

I am getting the grouped list as follows :- 我得到的分组列表如下:-

IEnumerable<List<AuditLog>> auditLogsGouped = auditLogs.GroupBy(x =>    x.EntityValue).Select(grp => grp.ToList());

How can I get the MAX 5 items from this list? 如何从此列表中获取MAX 5物品?

Thanks for your help and time 感谢您的帮助和时间

This should do a trick for you : 这应该为您提供了一个窍门:

auditLogsGouped.OrderBy(x=>x.Count).Reverse().Take(5);

or better: 或更好:

auditLogsGouped.OrderByDescending(x=>x.Count).Take(5);

You should take a look at Enumerable.Take . 您应该看看Enumerable.Take Here's the documentation and the relevant portion: 这是文档和相关部分:

public static IEnumerable<TSource> Take<TSource>(
        this IEnumerable<TSource> source,
  int count
)

Take enumerates source and yields elements until count elements have been yielded or source contains no more elements. 枚举source和yield元素,直到产生count元素或source不再包含任何元素为止。 If count exceeds the number of elements in source, all elements of source are returned. 如果count超过source中元素的数量,则返回source中的所有元素。

So this should do what you want by just calling .Take(5) 因此,只需调用.Take(5) ,即可完成您想要的操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM