2

There's got to be a better way!

I have a bunch 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.

fynnbob
  • 553
  • 1
  • 5
  • 14

1 Answers1

1
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.

xandy
  • 27,357
  • 8
  • 59
  • 64
  • This will return a very long list with a lot of days! You probably want to move 'DayOfWeek' into your 'GroupBy' instead of your 'Select'. – diceguyd30 Nov 12 '10 at 13:28
  • Thanks to both of you. xandy's answer returned a list with days of the week with a count of one and diceguyd30's comment to move 'DayOfWeek' to the GroupBy aggregated the list. Here is the code that worked for me: var weekDaySummary = someLogs.GroupBy(log => log.CreateDate.Value.DayOfWeek) .Select(list => new { WeekDay = list.Key, Count = list.Count() }) .OrderByDescending(list => list.Count); – fynnbob Nov 12 '10 at 17:28