im trying to extract the most common YEAR from an array of DateTime objects using LINQ.
can someone help me? With the follow开发者_运维问答ing 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();
int commonYear = dates.GroupBy(date => date.Year)
.OrderByDescending(g => g.Count())
.First().Key;
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.
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.
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;
精彩评论