C#
C#

help

Root Question Message

Gibin
Gibin1/11/2023
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
TheBoxyBear
TheBoxyBear1/11/2023
Like process one loan then one returned then one loan etc?
Gibin
Gibin1/11/2023
yes
TheBoxyBear
TheBoxyBear1/11/2023
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
TheBoxyBear
TheBoxyBear1/11/2023
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
Gibin1/11/2023
how do i implement this
TheBoxyBear
TheBoxyBear1/11/2023
using var loanEnumerator = loans.GetEnumerator()
TheBoxyBear
TheBoxyBear1/11/2023
And do the same for returns
Gibin
Gibin1/11/2023
okay thank you
TheBoxyBear
TheBoxyBear1/11/2023
You just have to check the return value of MoveNext every time
TheBoxyBear
TheBoxyBear1/11/2023
When it returns false, that means it was already pointing at the last item before the call
Gibin
Gibin1/11/2023
yesss
TheBoxyBear
TheBoxyBear1/11/2023
Or there are no items. The enumerator starts before the first item so you have to start with MoveNext
Gibin
Gibin1/11/2023
okay
TheBoxyBear
TheBoxyBear1/11/2023
And don't forget the using 🙂 no brackets needed in modern c#
TheBoxyBear
TheBoxyBear1/11/2023
Like with the StreamWriter
TheBoxyBear
TheBoxyBear1/11/2023
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
TheBoxyBear
TheBoxyBear1/11/2023
Then it's as simple as foreach (var item in listA.Alternate(listB))
TheBoxyBear
TheBoxyBear1/11/2023
public static AlternatingEnumerable<T> Alternate(this IEnumerable<T> first, params IEnumerable<T>[] others)
thinker227
thinker2271/11/2023
Btw you probably want to use properties instead of all those GetX methods.
Risa
Risa1/11/2023
^ this. properties are the elegant solution to getters and setters in languages like java
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy