views:

82

answers:

4

Hi, im trying to extract the most common YEAR from an array of DateTime objects using LINQ.

can someone help me? With the following its telling me i need to implement IComparable..

            DateTime modeDate = (from c in dates 
                                 group c by c.Year into g 
                                 select g).Max().First();
+2  A: 

I think you're pretty close.

var dateUsedMostOften = (from d in dates
                         group d by d.Year into y
                         orderby y.Count() descending
                         select y).First().Key;

Untested. See if that works.

Note: If there are no items in the list this'll probably fail. You could get around it by calling FirstOrDefault() and then testing if that has returned null. Only look for .Key if you know it's non-null.

Matt Hamilton
That'll return a grouping. You want to do `.First().Key`, which will return an `int` corresponding to the most common year.
Sapph
Yes, a good point. I'll update it so as not to confuse new readers.
Matt Hamilton
+2  A: 

This part of your query

from c in dates 
    group c by c.Year into g 
    select g

returns an IGrouping<int, DateTime> and that does not implement ICompareable

other people have provided good answers for the query you want, but I thought you might want to know where the original error came from.

Mike Two
+3  A: 
int commonYear = dates.GroupBy(date => date.Year)
                      .OrderByDescending(g => g.Count())
                      .First().Key;
Kobi
This works great, but it is ambiguous when there is more than one year with the same max frequency. Of course the original question doesn't provide any hints on how they need to solve that part, but it is a potential gotcha.
Mike Two
@Mike Two - Excellent point, I didn't think of that (which is concerning to me :) ).
Kobi
+1  A: 

This should do the job.

        List<DateTime> list = new List<DateTime> ();
        list.Add (DateTime.Parse ("2002 Jan 01"));
        list.Add (DateTime.Parse ("2003 Jan 01"));
        list.Add (DateTime.Parse ("2004 Jan 01"));
        list.Add (DateTime.Parse ("2005 Jan 01"));
        list.Add (DateTime.Parse ("2004 Jan 01"));
        list.Add (DateTime.Parse ("2004 Jan 01"));
        list.Add (DateTime.Parse ("2007 Jan 01"));

        int year = list.Select (d => d.Year)
            .GroupBy (y => y)
            .OrderBy (g => g.Count ())
            .Last ()
            .Key;
Jacques Bosch