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

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);
    }
}

Tags:

C#

List