John A Grandy wrote:
Is it possible to write a foreach so that it simultaneously iterates through
two collections ( or two properties of the same collection ) ?
No, because there's no meaningful definition of "simultaneous" (what should
happen if one of the iterations is done before the other one?)
Following is *only meant as an example* :
-- iterate a dictionary obtaining the next key and value on each iteration.
The following doesn't work
foreach ( string key in MyDictionary.Keys , object value in
MyDictionary.Values )
{
... but perhaps there's some other way ...
What type is "MyDictionary"? It should implement
IEnumerable<KeyValuePair<TKey, TValue>>, like IDictionary<TKey, TValue>
does. Then it's a matter of writing
foreach (KeyValuePair<string, objectp in MyDictionary) {
string key = p.Key;
object value = p.Value;
...
}
If it's one of the legacy collection types that has no intuitive IEnumerable
implementation, it's a simple matter of iterating over the keys only:
foreach (string key in MyDictionary.Keys) {
object value = MyDictionary[key];
...
}
Of course, since you specify that this is only "an example", you may not be
talking about dictionaries at all. It's always possible to use enumerators
directly for advanced scenarios:
using (IEnumerator<stringiKeys = MyDictionary.Keys.GetEnumerator()) {
using (IEnumerator<objectiObject = MyDictionary.Values.GetEnumerator()) {
// use .MoveNext() and .Current here as you please
}
}
But this is seldom necessary, and the resulting code isn't very readable.
--
J.