Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need the Index of the last item in a List, how?

Tags:

c#

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.

like image 486
iAmThatOneDuck Avatar asked Nov 30 '25 16:11

iAmThatOneDuck


1 Answers

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(); 
like image 150
Alexei Levenkov Avatar answered Dec 02 '25 06:12

Alexei Levenkov