1 回答
TA贡献1848条经验 获得超2个赞
您可以使用GroupBy
LINQ 中的方法来完成此操作,该方法
根据指定的键选择器函数对序列的元素进行分组
在您的情况下,关键是year
语法GroupBy
如下所示:
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);
}
}
其产生的输出为:
- 1 回答
- 0 关注
- 99 浏览
添加回答
举报