217

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");
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
learnerplates
  • 4,257
  • 5
  • 33
  • 42
  • Possible duplicate? http://stackoverflow.com/questions/7850334/how-to-convert-ienumerable-of-keyvaluepairx-y-to-dictionary – Coolkau Oct 18 '16 at 10:13

2 Answers2

378

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.

Roy Tinker
  • 10,044
  • 4
  • 41
  • 58
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 18
    You'd think there would be a call that doesn't require arguments, given that Dictionary implements IEnumerable>, but oh well. Easy enough to make your own. – Casey Apr 08 '14 at 21:00
  • 1
    @emodendroket why would you think that? You can cast the Dictionary directly to the IEnumerable mentioned because of the interface, but not the other way around. i.e. `IEnumerable>` does not implement or inherit `Dictionary`. – djv Jul 01 '14 at 15:40
  • 6
    @DanVerdolino I know that. You'd think that because it's like one of the most common things you might want to do with an IEnumerable of KVPs. – Casey Jul 01 '14 at 15:42
  • 22
    2016 now, and I still had to google this. You'd think that there would be a constructor for `Dictionary` that took a `IEnumerable>` just like `List` takes a `IEnumerable`. Also there is no `AddRange` or even `Add` that takes key/value pairs. What's up with that? – mausworks Sep 03 '16 at 15:46
  • 6
    It's 2017 now, and we can add this as an extension method! – Chris Bush May 10 '17 at 21:39
  • 3
    A lot of "I can't believe .net core doesn't have " is resolved via [MoreLinq](https://www.nuget.org/packages/morelinq/). Including a parameterless IEnumerable -> `ToDictionary()` – aaaaaa Dec 06 '17 at 21:42
  • 1
    `public static Dictionary ToDictionary(this IEnumerable> source) => source.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);` If you read this far and are still wanting, here is this answer as an extension method. – Tom Blodget Aug 09 '19 at 18:26
28

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

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Mason Kerr
  • 391
  • 3
  • 7