开发者

How to iterate over two Collections?

开发者 https://www.devze.com 2023-02-09 19:47 出处:网络
I\'d like to use a for each loop to iterate over two Collections. My first ide开发者_运维问答a was:

I'd like to use a for each loop to iterate over two Collections. My first ide开发者_运维问答a was:

foreach (object o in a.Concat(b)) {

o.DoSomething(); }

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号