【问题标题】:Convert an array of objects to a dictionary of objects将对象数组转换为对象字典
【发布时间】:2010-09-04 18:46:31
【问题描述】:

我有一系列事件:

IEnumerable<CalendarEvent> events

我想把它转换成字典,所以我试了一下:

   Dictionary<string, CalendarEvent> dict = events.ToDictionary(r => r.Date.ToString("MMM dd, yyyy"));

问题是我在一个日期有多个事件,所以我需要一种方法将其转换为一个

Dictionary<string, List<CalendarEvent>> 

支持有多个事件的日子

【问题讨论】:

    标签: c# collections dictionary


    【解决方案1】:

    您可以改用ToLookup

    var lookup = events.ToLookup(r => r.Date.ToString("MMM dd, yyyy"));
    

    当您为查找编制索引时,您会获得所有匹配结果的可枚举,因此在该示例中,lookup["Sep 04, 2010"] 将为您提供IEnumerable&lt;CalendarEvent&gt;。如果没有结果匹配,您将得到一个空的可枚举而不是 KeyNotFoundException。

    您也可以使用GroupBy,然后使用 ToDictionary:

    Dictionary<string, List<CalendarEvent>> dict = events
        .GroupBy(r => r.Date.ToString("MMM dd, yyyy"))
        .ToDictionary(group => group.Key, group => group.ToList());
    

    【讨论】:

      猜你喜欢
      • 2018-07-15
      • 1970-01-01
      • 2018-04-13
      • 2020-06-15
      • 2016-03-11
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多