Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Split list into sublists based on a value of a certain property?

Tags:

c#

list

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
        });
    }
like image 970
Erica Stockwell-Alpert Avatar asked Oct 15 '14 13:10

Erica Stockwell-Alpert


2 Answers

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
}
like image 53
Vladimirs Avatar answered Sep 22 '22 23:09

Vladimirs


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);
    }
}
like image 12
Matt Burland Avatar answered Sep 20 '22 23:09

Matt Burland