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.
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?