❔ C# forloops
is there a way i can let 2 for loops run but then switching turns kinda,
For example if the first forloop only outputs 1s and the second one only 2s, i want the output to be 121212 instead of 111222
15 Replies
Like process one loan then one returned then one loan etc?
yes
https://stackoverflow.com/questions/20141241/selecting-alternate-items-of-an-array-c-sharp Similar to this, but you would need to combine both collections first with Concat
Stack Overflow
Selecting alternate items of an array C#
I have an array statsname as
apple
X
banana
Y
Kiwi
z
I need to put apple,banana and Kiwi in an array Fruits and X,Y and Z in an array called alphabets.
Any simple C# mechanism for it please ?
For better performance, you can also do low level enumeration by getting the enumerator from each collection. The enumerator has a MoveNext method to move to the next item and a Current property to get the item it's currently pointing at
how do i implement this
using var loanEnumerator = loans.GetEnumerator()
And do the same for returnsokay thank you
You just have to check the return value of MoveNext every time
When it returns false, that means it was already pointing at the last item before the call
yesss
Or there are no items. The enumerator starts before the first item so you have to start with MoveNext
okay
And don't forget the using 🙂 no brackets needed in modern c#
Like with the StreamWriter
I had this problem once and made a custom collection class that takes multiple enumerables and uses a custom enumerator that handles all the alternating logic when MoveNext is called
Then it's as simple as
foreach (var item in listA.Alternate(listB))
public static AlternatingEnumerable<T> Alternate(this IEnumerable<T> first, params IEnumerable<T>[] others)
Btw you probably want to use properties instead of all those
GetX
methods.^ this. properties are the elegant solution to getters and setters in languages like java
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.