Elmo
Elmo

Reputation: 6471

For Each Element in Two Lists

This is my code:

List<string> l1 = new List<string> { "a", "b", "c" };
List<string> l2 = new List<string> { "x", "y", "z" };
foreach (var item in l1)
{
    item = MyFunction(item);
}
foreach (var item in l1)
{
    item = MyFunction(item);
}

Is there a way to iterate both the Lists in a single foreach statement ?

Upvotes: 1

Views: 177

Answers (3)

Randy Minder
Randy Minder

Reputation: 48402

Maybe something like this:

var mergedList = 11.Union(l2).ToList();
foreach (var item in mergedList)
{
    item = MyFunction(item);
}

The Union removes any duplicates. The Concat() method does not. So Union might be preferrable. It depends on the composition of the lists.

Upvotes: 0

KeithS
KeithS

Reputation: 71565

You could use the Concat() function:

foreach(var item in l1.Concat(l2))
   item = MyFunction(item);

Be aware that reassigning the counter variable of an Enumerable-based loop can cause exceptions relating to changing the underlying IEnumerable.

Upvotes: 4

Servy
Servy

Reputation: 203814

Assuming the type of the List objects are the same you can use Concat.

foreach (var item in l1.Concat(l2))
{
    item = MyFunction(item);
}

Upvotes: 7

Related Questions