Querying a List of objects to find the the day of the week with the most items
There's got to be a better way!
I have a bun开发者_JAVA百科ch of log records stored in a List. Each log record has a CreateDate field and what I'm trying to do is find an efficient way to query the List object to find the day of the week with the most log records (Monday, Tuesday, etc...).
I'm thinking that this can be done using Linq but I don't know Linq well enough. It may be that I'll have to do this the long way by getting a count for each specific day and then comparing them against each other to find the day with the most logs but I'm hoping that someone will be able to show me a cool way to do it.
Thanks.
Loglist.GroupBy(log => log.CreateDate)
.Select(list => new { DayOfWeek = list.Key.DayOfWeek, Count = list.Count()})
.OrderByDescending(list=>list.Count);
This will return a list of (DayOfWeek, Count) in Descending Order. If you need only the largest count dayofweek, apply .First()
at the end of the above list.
精彩评论