繁体   English   中英

如何转换清单 <CustomType> 到字典 <int, List<CustomType> &gt;

[英]How to convert List<CustomType> to Dictionary<int, List<CustomType>>

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

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

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

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

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

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

在您的情况下,键将是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);
    }
}

产生的输出为:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM