ryrich
ryrich

Reputation: 2204

Using a foreach loop on a List of two types?

I know I can use a foreach loop as follows:

List<int> handles = GetHandles();

foreach (int handle in handles)
{
    // do stuff
}

Can I do the same for a SortedList as follows?

SortedList<string, int> namesAndHandles;

EDIT: Sorry, made a typo. It should be a SortedList. Essentially I want to convert this to an IDictionary and access the handles based off a name

Upvotes: 1

Views: 885

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503629

There's no such thing as List<string, int> - there's no List<,> type with two type parameters. If you've got a collection of name/handle pairs, you should either use List<Tuple<string, int>> or create your own NameAndHandle class. Either will work fine with foreach.

(You could create your own List<TFirst, TSecond> class if you really wanted, but I'd really advise against it.)

Upvotes: 5

Jason
Jason

Reputation: 15931

I bet List<KeyValuePair<string,int>> would do what you are looking for. You could iterate the collection and the .Key property holds the string and .Value holds the int

Upvotes: 0

Related Questions