I have a list of events, each of which has a datetime property. I need to split the list up into sublists by year. The trick is, my list of events is pulled from a database and subject to change, so I can't just hardcode the set of years and sort the events into the right year. Is there a way that I can split my main list of events into sublists so that within each sublist, each event has the same year? So I would end up with a sublist of all 2010 events, a sublist of all 2011 events, and so on.
My list is created like this :
foreach (var ev in eventResults)
{
eventsList.Add(new Event()
{
Name = ev.Title,
Month = CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(ev.StartDate.Month),
Day = ev.StartDate.Day,
Year = ev.StartDate.Year
});
}
You need to make a grouping by year like this:
eventsList.GroupBy(x => x.Year)
So later you will be able to iterate through result of code above:
foreach (var eventsInYear in eventsList.GroupBy(x => x.Year))
{
// eventsInYear.Key - year
// eventsInYear - collection of events in that year
}
Use GroupBy:
var eventsByYear = eventsList.GroupBy(a => a.Year);
You can then iterate through that collection to process each year:
foreach (var yearEvents in eventsByYear)
{
// yearEvents contains all the events for one particular year
Console.WriteLine("Events for year: " + yearEvents.Key);
foreach (var e in yearEvents)
{
Console.WriteLine(e);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With