Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将对象数组转换为对象字典_C#_Collections_Dictionary - Fatal编程技术网

C# 将对象数组转换为对象字典

C# 将对象数组转换为对象字典,c#,collections,dictionary,C#,Collections,Dictionary,我有一系列事件: IEnumerable<CalendarEvent> events IEnumerable事件 我想将其转换为字典,因此我尝试了以下方法: Dictionary<string, CalendarEvent> dict = events.ToDictionary(r => r.Date.ToString("MMM dd, yyyy")); Dictionary dict=events.ToDictionary(r=>r.Date.ToSt

我有一系列事件:

IEnumerable<CalendarEvent> events
IEnumerable事件
我想将其转换为字典,因此我尝试了以下方法:

   Dictionary<string, CalendarEvent> dict = events.ToDictionary(r => r.Date.ToString("MMM dd, yyyy"));
Dictionary dict=events.ToDictionary(r=>r.Date.ToString(“MMM-dd,yyyy”);
问题是我在一个日期有多个事件,所以我需要一种方法将其转换为

Dictionary<string, List<CalendarEvent>> 
字典
要支持具有多个事件的日期,可以改用

var lookup = events.ToLookup(r => r.Date.ToString("MMM dd, yyyy"));
为查找编制索引时,会得到所有匹配结果的可枚举结果,因此在该示例中,
lookup[“Sep 04,2010”]
将为您提供一个
IEnumerable
。如果没有匹配的结果,您将得到一个空的枚举,而不是KeyNotFoundException

您还可以使用,然后使用:

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