2

I want to create a method that would iterate through a keyed collection. I want to make sure that my method support iteration of any collection that extends the KeyedCollection<string, Collection<string>>

Here's the method:

public void IterateCollection(KeyedCollection<string, Collection<string>> items)
{
    foreach (??? item in items)
    {
        Console.WriteLine("Key: " + item.Key);
        Console.WriteLine("Value: " + item.Value);
    }
}

It doesn't work obviously because I don't know which type should replace the question marks in the loop. I cannot simply put object or var because I need to call the Key and Value properties later on in the loop body. What is the type that I am looking for? Thanks.

Boris
  • 9,986
  • 34
  • 110
  • 147
  • 1
    You should consider using ReSharper or any other code assisting tool in your aid. ReSharper will give you an option to specify the type explicitly when you use var. So you could've solved this by a simple key combination in ReSharper (alt-enter) – edvaldig Nov 11 '11 at 14:18
  • And if you call dynamic to the rescue? In your case, item will be Collection wich is what KeyedCollection will return, KeyedCllection will return always , check this out: http://msdn.microsoft.com/en-us/library/ms132438.aspx – VoidMain Nov 11 '11 at 14:22

2 Answers2

8

KeyedCollection<TKey, TItem> implements ICollection<TItem>, so in this case you'd use:

foreach(Collection<string> item in items)

That's what var would give you as well. You don't get key/value pairs in KeyedCollection - you just get the values.

Is it possible that KeyedCollection really isn't the most appropriate type for you to be using?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks Jon. I do need the collection of key/value pairs, so I am wrong for using `KeyedCollection`. Could you please recommend me a class that is as abstract as possible, but could serve my purpose? Thanks. – Boris Nov 11 '11 at 14:16
  • 1
    @Boris: Just `IDictionary` would be my suggestion. – Jon Skeet Nov 11 '11 at 14:17
2

The item type is going to be Collection<String> by definition of the enumerator of KeyedCollection. You can't arbitrarily decide on using an appropriate type so that you get both Key and Value if the iteration doesn't support it, which it doesn't in this case. Note that using the explicit type and var are exactly identical.

If you want both Key and Value available in iteration, you need to use the Dictionary<string, Collection<string>> type.

mellamokb
  • 56,094
  • 12
  • 110
  • 136
  • mellamokb, thanks for the clarification on explicit types and vars. Could you recommend a class that might serve my purpose? I need a collection of key/value pairs. Thanks! – Boris Nov 11 '11 at 14:18