Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

C#CollectionsDictionaryIenumerableIdictionary

C# Problem Overview


I have a method that returns an IEnumerable<KeyValuePair<string, ArrayList>>, but some of the callers require the result of the method to be a dictionary. How can I convert the IEnumerable<KeyValuePair<string, ArrayList>> into a Dictionary<string, ArrayList> so that I can use TryGetValue?

method:

public IEnumerable<KeyValuePair<string, ArrayList>> GetComponents()
{
  // ...
  yield return new KeyValuePair<string, ArrayList>(t.Name, controlInformation);
}

caller:

Dictionary<string, ArrayList> actual = target.GetComponents();
actual.ContainsKey("something");

C# Solutions


Solution 1 - C#

If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

Solution 2 - C#

As of .NET Core 2.0, the constructor Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) now exists.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlearnerplatesView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#Mason KerrView Answer on Stackoverflow