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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.