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

时间:2019-08-09 23:46:39

标签: c# .net

让我们说我们有这种自定义类型:

y

我需要将假期(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>)。键是不同的年份,值是属于年份的假期列表。

我试图通过查看此answer/Question来做到这一点,但没有成功。

1 个答案:

答案 0 :(得分:5)

您可以使用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);
    }
}

哪个输出为:

enter image description here