So, I've been searching for a while but didn't really find any results.
For example I have this list:
List<int> intList = new List<int>{1, 2, 3, 4, 1}
And I want to output in my console "Numbers: 1, 2, 3, 4 and 1", that doesn't make it hard. But I want to be able to use User-inputted numbers, and for the last number it has to have the "and" before the number instead of the comma. The things I've tried so far resulted in the problem that any item with the same value also had the "and" instead of the comma.
Examples of what I've used in the if-statement in my for-loop that resulted in any equal values as last one also having the "and":
if (intList[i] == intList.Last())
if(intList[i] == intList[intList.Count - 1])
It seems logic to me why these didn't work, but understanding the problem and fixing it are still 2 different things.
Join everything before the .Last() and than concatenate with " and " + Last() like:
string result = intList.Count <= 1 ?
string.Join(", ", intList) :
string.Join(", ", intList.Take(intList.Count - 1)) + " and " + intList.Last();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With