C
C#2y ago
Gibin

❔ 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
TheBoxyBear
TheBoxyBear2y ago
Like process one loan then one returned then one loan etc?
Gibin
GibinOP2y ago
yes
TheBoxyBear
TheBoxyBear2y ago
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 ?
TheBoxyBear
TheBoxyBear2y ago
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
Gibin
GibinOP2y ago
how do i implement this
TheBoxyBear
TheBoxyBear2y ago
using var loanEnumerator = loans.GetEnumerator() And do the same for returns
Gibin
GibinOP2y ago
okay thank you
TheBoxyBear
TheBoxyBear2y ago
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
Gibin
GibinOP2y ago
yesss
TheBoxyBear
TheBoxyBear2y ago
Or there are no items. The enumerator starts before the first item so you have to start with MoveNext
Gibin
GibinOP2y ago
okay
TheBoxyBear
TheBoxyBear2y ago
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)
Thinker
Thinker2y ago
Btw you probably want to use properties instead of all those GetX methods.
risanha
risanha2y ago
^ this. properties are the elegant solution to getters and setters in languages like java
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server