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>implementsICollection<TItem>, so in this case you’d use:That’s what
varwould give you as well. You don’t get key/value pairs inKeyedCollection– you just get the values.Is it possible that
KeyedCollectionreally isn’t the most appropriate type for you to be using?