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

1 Answer 1

3

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.