简体   繁体   中英

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.

Now I want to get Max 5 items, ie those that have the most items inside this 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?

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 . 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. If count exceeds the number of elements in source, all elements of source are returned.

So this should do what you want by just calling .Take(5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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