Why doesn't this code compile?

  • Thread starter Thread starter Dave
  • Start date Start date
D

Dave

This code generates the following error:

Error 2 Cannot convert type
'System.Collections.Generic.KeyValuePair<string,CollectionTest.Group>' to
'CollectionTest.Group' C:\Code\Project\CollectionTest.cs 21 4 Project

How do I use foreach to iterate through the Groups collection??



public class Group
{
}

public class Groups : SortedList<string, Group>
{
}

public class TestIt
{
public void Test()
{
Groups groups = new Groups();

foreach (Group group in groups)
{
}
}
}
 
Ok, needed to use groups.Values instead of just groups.

foreach (Group group in groups.Values)
 
Yes. If you iterate over a Dictionary type (SortedList, Hashtable)
directly, what you get back is some sort of dictionary entry that
comprises a key and a value.

If you want just the values (or, perhaps, just the keys), you have to
say that explicitly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top