views:

38

answers:

1

i have an array of events:

IEnumerable<CalendarEvent> events

i want to convert this to a dictionary so i tried this:

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

the issue is that i have multiple events on a single date so i need a way to convert this to a

Dictionary<string, List<CalendarEvent>> 

to support the days which have multiple events

+2  A: 

You can use ToLookup instead.

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

When you index a lookup, you get an enumerable of all matching results, so in that example lookup["Sep 04, 2010"] would give you an IEnumerable<CalendarEvent>. If no results match, you will get an empty enumerable rather than a KeyNotFoundException.

You could also use GroupBy and then ToDictionary:

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