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.
精彩评论