c# - How to iterate through two IEnumerables simultaneously? -
i have enumerables ienumerable<a> list1
, ienumerable<b> list2
, iterate through them simultaneously like:
foreach((a, b) in (list1, list2)) { // use , b }
if not contain same number of elements, exception should thrown.
what best way this?
here's implementation of operation, typically called zip:
using system; using system.collections.generic; namespace so2721939 { public sealed class zipentry<t1, t2> { public zipentry(int index, t1 value1, t2 value2) { index = index; value1 = value1; value2 = value2; } public int index { get; private set; } public t1 value1 { get; private set; } public t2 value2 { get; private set; } } public static class enumerableextensions { public static ienumerable<zipentry<t1, t2>> zip<t1, t2>( ienumerable<t1> collection1, ienumerable<t2> collection2) { if (collection1 == null) throw new argumentnullexception("collection1"); if (collection2 == null) throw new argumentnullexception("collection2"); int index = 0; using (ienumerator<t1> enumerator1 = collection1.getenumerator()) using (ienumerator<t2> enumerator2 = collection2.getenumerator()) { while (enumerator1.movenext() && enumerator2.movenext()) { yield return new zipentry<t1, t2>( index, enumerator1.current, enumerator2.current); index++; } } } } class program { static void main(string[] args) { int[] numbers = new[] { 1, 2, 3, 4, 5 }; string[] names = new[] { "bob", "alice", "mark", "john", "mary" }; foreach (var entry in numbers.zip(names)) { console.out.writeline(entry.index + ": " + entry.value1 + "-" + entry.value2); } } } }
to make throw exception if 1 of sequences run out of values, change while-loop so:
while (true) { bool hasnext1 = enumerator1.movenext(); bool hasnext2 = enumerator2.movenext(); if (hasnext1 != hasnext2) throw new invalidoperationexception("one of collections ran " + "out of values before other"); if (!hasnext1) break; yield return new zipentry<t1, t2>( index, enumerator1.current, enumerator2.current); index++; }
Comments
Post a Comment