anon
anon

Reputation:

How to iterate over two Collections?

I'd like to use a for each loop to iterate over two Collections. My first idea was:

foreach (object o in a.Concat(b)) {
o.DoSomething(); }

But the problem is, not all Collections support Concat. So what do to?

Upvotes: 1

Views: 437

Answers (2)

Mark Byers
Mark Byers

Reputation: 838876

Some legacy collection types implement only IEnumerable and not IEnumerable<T>, and therefore don't have the Concat extension method. You can solve this by first using the method Enumerable.Cast<T> and specifying the generic type you want, then it will work with Concat.

Upvotes: 2

Edwin Buck
Edwin Buck

Reputation: 70949

Instead of ...

foreach (object o in a.Concat(b)) {
o.DoSomething(); }

Why not just ?

foreach (object o in a) {
  o.DoSomething();
}
foreach (object o in b) {
  o.DoSomething();
}

If you really want them to be both in the same list, construct a new list and add them together before you start processing.

Upvotes: 1

Related Questions