C
C#2y ago
jseb

List output with Console.Write

Hello, i try to output a Fibonacci list with ';' as separator. I don't want ';' after the last item, so i make it in a quite complicated way.
var fb = new List<int> {1, 1};

for (int i=0; i<10; i++) {
fb.Add(fb[i]+fb[i+1]);
}

foreach(var n in fb) {
var sep="; ";
if (n==fb[fb.Count-1]) { sep=""; }
Console.Write($"{n}{sep}");
}
var fb = new List<int> {1, 1};

for (int i=0; i<10; i++) {
fb.Add(fb[i]+fb[i+1]);
}

foreach(var n in fb) {
var sep="; ";
if (n==fb[fb.Count-1]) { sep=""; }
Console.Write($"{n}{sep}");
}
any suggestions, please ?
3 Replies
jseb
jsebOP2y ago
well anyway, getting fb last value with index ugly and slow (as recomputed at each iteration) so at least i can propose:
var fb = new List<int> {1, 1};

for (int i=0; i<10; i++) {
fb.Add(fb[i]+fb[i+1]);
}

int last=fb.Last();
foreach(var n in fb) {
var sep="; ";
if (n == last) { sep=""; }
Console.Write($"{n}{sep}");
}
var fb = new List<int> {1, 1};

for (int i=0; i<10; i++) {
fb.Add(fb[i]+fb[i+1]);
}

int last=fb.Last();
foreach(var n in fb) {
var sep="; ";
if (n == last) { sep=""; }
Console.Write($"{n}{sep}");
}
HimmDawg
HimmDawg2y ago
Right, so first, you should declare var sep = "; " outside of the loop, since it doesn't change. Other than that you figured out a way, which is good owo But now you can upgrade: string.Join("; ", fb) will give you the string you want Where the first argument of string.Join is the delimiter you want to use and the second argument is any enumerable (lists, collections, etc.) Also a hint for the future: If there's no handy function like string.Join, you might wanna use the item index to determine if you are at the end of an array. This does not run the risk of recomputing the last element or running an overly complicated comparison if the list contains objects
jseb
jsebOP2y ago
ah nice concatenation function ! I will now explore string class, to see what it offers. Thank you for the help.
Want results from more Discord servers?
Add your server