all groups > dotnet general > may 2007 >
You're in the

dotnet general

group:

How to enumerate two collections in the same loop?


How to enumerate two collections in the same loop? Andrew
5/31/2007 4:33:01 PM
dotnet general:
Hello, friends,

In c#.net, can we enumerate two collections in the same loop? For example:

foreach (int amount in AmountCollection && string lastName in
LastNameCollection)
{
Console.WriteLine(lastName + " made $" + amount.ToString() + " this
week.");
}

Can we do something like this in .net? If yes, what is the correct syntax?
If not, how to do this operation this efficiently?

Re: How to enumerate two collections in the same loop? Chris Mullins [MVP]
5/31/2007 5:15:16 PM
You could do something like:

foreach(int i = 0; i < collection1.Count; i++)
{
string s1 = collection1[i];
string s2 = collection2[i];

string s3 = s1 + " : " + s2;
}

There are a number of other variations on that theme you could use.

Keep in mind, clarity of code is the most important thing. If you're playing
weird syntax games in C#, then you're probably going to end up having bugs
either now, or further down the line.

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, Microsoft C# MVP
http://www.coversant.com/blogs/cmullins


[quoted text, click to view]

Re: How to enumerate two collections in the same loop? Marc Gravell
6/1/2007 12:00:00 AM
Of course, you could keep the values on the same entity? i.e. a class
with the Name and Amount properties, and a single list?

With 2 lists, the alternative to indexers (as Chris suggests) is to
increment two enumerators in parallel ("using" here is to keep close
to foreach, but is probably not strictly needed):

using(IEnumerator<int> aIterator = aList.GetEnumerator())
using (IEnumerator<string> bIterator =
bList.GetEnumerator()) {
while (aIterator.MoveNext() && bIterator.MoveNext()) {
int a = aIterator.Current;
string b = bIterator.Current;
Console.WriteLine(b + " made $" + a.ToString() + "
this week.");
}
}

But as Chris says; use whichever syntax you find clearest - there
isn't likely to be much of a performance hit either way.

Marc

Re: How to enumerate two collections in the same loop? Göran Andersson
6/2/2007 1:17:03 PM
[quoted text, click to view]

The foreach statement can't handle more than one enumerator, but you can
do it yourself. Something like:

IEnumerator<int> amounts = AmountCollection.GetEnumerator();
IEnumerator<string> names = LastNameCollection.GetEnumerator();
while (amounts.MoveNext() && names.MoveNext()) {
Console.WriteLine(names.Current + " made $" +
amounts.Current.ToString() + " this week.");
}

Note that if the collections are not of the same size, the loop will end
when the first enumerator reaches the end of it's collection.

--
Göran Andersson
_____
AddThis Social Bookmark Button