Reputation: 313
Lets say that we have this custom type:
public class Holiday
{
public Guid Id { get; } = Guid.NewGuid();
public string holidayName { get; set; };
public DateTime fromDate { get; set; };
public DateTime toDate { get; set; };
public int year { get; set; };
}
I need to convert list of Holidays (List<Holiday>
) to an dictionary (Dictionary<int, List<Holiday>>
). The keys are distinct years and the values are Lists of Holidays those belong to year.
I have tried to do that by looking at this answer/Question but without success.
Upvotes: 1
Views: 106
Reputation: 4219
You can do this using the GroupBy
method in LINQ, which
Groups the elements of a sequence according to a specified key selector function
In your case, the key would be year
so the GroupBy
syntax would look as follows:
List<Holiday> holidays = new List<Holiday>
{
new Holiday
{
year = 1999,
holidayName = "Easter"
},
new Holiday
{
year = 1999,
holidayName = "Christmas"
},
new Holiday
{
year = 2000,
holidayName = "Christmas"
}
};
Dictionary<int, List<Holiday>> holidaysByYear = holidays
.GroupBy(h => h.year)
.ToDictionary(h => h.Key, h => h.ToList());
foreach (KeyValuePair<int, List<Holiday>> holidaysInYear in holidaysByYear)
{
Console.WriteLine($"Holidays in {holidaysInYear.Key}");
foreach (Holiday holiday in holidaysInYear.Value)
{
Console.WriteLine(holiday.holidayName);
}
}
Which produces output as:
Upvotes: 7