Python's iter(.) and next(.) built-in functions allow iterating a list (or other objects that implement __iter__(self) and __next__(self)) without a for loop and without an index.
Does C# have something equivalent to iter(.) and next(.)? The
Say that for some reason you wanted to merge two lists sorted numbers without using for loops nor indices. You could do so using iterators and next(.) as follows:
def merge(nums1, nums2):
nums1Iter = iter(nums1)
nums2Iter = iter(nums2)
num1 = next(nums1Iter)
num2 = next(nums2Iter)
while True:
if num1 <= num2:
yield num1
try:
num1 = next(nums1Iter)
except StopIteration:
yield num2
yield from nums2Iter
break
else:
yield num2
try:
num2 = next(nums2Iter)
except StopIteration:
yield num1
yield from nums1Iter
break
nums1 = range(0, 10, 2)
nums2 = range(1, 20, 3)
print(list(merge(nums1, nums2)))
Yes, C# calls them Enumerators. The
IEnumerator InterfaceandIEnumerator<T> Interfaceeach have aMoveNextmethod aCurrentproperty which you can use to iterate without for loops nor indices as follows:would print out:
Notes:
GetEnumeratormethod which you can use to get an Enumerator of the Array, List, etc. object.IEnumerator.Currentis of typeobjectso you have to do an explicit cast if assigning its value to a typed variable (not sure if typed variable is the appropriate terminology here). Otherwise, you'll get aCannot implicitly convert type 'object' to ...error.