如何将List <CustomType>转换为Dictionary <int,List <CustomType >>

Bor*_*vic 0 .net c#

可以说我们有这个定制类型:

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; };
}
Run Code Online (Sandbox Code Playgroud)

我需要将“假日”列表(List<Holiday>)转换为字典(Dictionary<int, List<Holiday>>)。键是不同的年份,值是属于年份的假期列表。

我试图通过查看此答案/问题来做到这一点, 但没有成功。

dev*_*ull 5

您可以使用GroupByLINQ中的方法执行此操作,

根据指定的键选择器功能对序列的元素进行分组

在你的情况,关键是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);
    }
}
Run Code Online (Sandbox Code Playgroud)

产生的输出为:

在此处输入图片说明