How to enumerate two collections in the same loop?

G

Guest

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?

Thanks a lot.
 
C

Chris Mullins [MVP]

You could do something like:

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

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.
 
M

Marc Gravell

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
 
G

Guest

Andrew said:
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?

Thanks a lot.

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.
 

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

Top