Recreating a Dictionary from an IEnumerable<KeyValuePair<>>
Asked Answered
X

2

219

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");
Xhosa answered 14/4, 2010 at 10:31 Comment(2)
Possible duplicate? #7850834Pursuance
@Pursuance That other question is newer and has fewer votes. I voted to close it as the dupe. Quality of answers seems, at worst, similar.Letitialetizia
A
382

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.

Aureole answered 14/4, 2010 at 10:35 Comment(7)
You'd think there would be a call that doesn't require arguments, given that Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>, but oh well. Easy enough to make your own.Hiroshima
@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<KeyValuePair<TKey, TValue>> does not implement or inherit Dictionary<TKey, TValue>.Castigate
@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.Hiroshima
2016 now, and I still had to google this. You'd think that there would be a constructor for Dictionary that took a IEnumerable<KeyValuePair<TKey, TValue>> just like List<T> takes a IEnumerable<T>. Also there is no AddRange or even Add that takes key/value pairs. What's up with that?Croat
It's 2017 now, and we can add this as an extension method!Crumby
A lot of "I can't believe .net core doesn't have <obvious feature>" is resolved via MoreLinq. Including a parameterless IEnumerable<KeyValuePair> -> ToDictionary()Inunction
public static Dictionary<TKey,TValue> ToDictionary<TKey,TValue>(this IEnumerable<KeyValuePair<TKey,TValue>> 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.Crowd
L
32

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

Logroll answered 26/4, 2020 at 14:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.