views:

164

answers:

1

But some of the callers is the Dictionary's TryGetValue and ContainsKey and so 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 ?

I've a method which at present returns an IEnumerable<KeyValuePair<string, ArrayList>>. I want to make it more generic by making it return an IEnumerable<string, ArrayList>.

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");
+1  A: 

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

Dictionary<string, ArrayList> = 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.

Jon Skeet
+1: Can't believe it's taken over 4 months and 80 views!
Alex Humphrey
Can't belineve JS actually found this burried question (and who knows how many more like it)!
Cristi Diaconescu
@Cristi: It wasn't buried when I answered it, four minutes after it was asked.
Jon Skeet