iAmThatOneDuck
iAmThatOneDuck

Reputation: 41

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

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.

Upvotes: 2

Views: 224

Answers (5)

Daniel Lorenz
Daniel Lorenz

Reputation: 4346

If it doesn't need to be too efficient, you can cheat a little like this:

 var result = string.Join(", ", intList);
 var lastCommaIndex = result.LastIndexOf(',');
 if (lastCommaIndex > 0)
 {
     result = result.Substring(0, lastCommaIndex) + " and" + result.Substring(lastCommaIndex + 1);
 }

Otherwise, @Alexei Levenkov answer is roughly what I'd do. :)

Upvotes: 1

Yoosh
Yoosh

Reputation: 67

You can also create a shallow copy of the original list using GetRange and exclude the last element.

    static void Main(string[] args)
    {
        List<int> intList = new List<int> {1, 2, 3, 4, 1};
        List<int> allButLast = intList.GetRange(0, intList.Count - 1);
        string last = intList.Last().ToString();
        string allButLastString = string.Join(',', allButLast);
        Console.WriteLine($"{allButLastString} and {last}");
    }

Upvotes: 1

Moises Puesto
Moises Puesto

Reputation: 41

Maybe this code can help you

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> intList = new List<int>{1,2,3,4,1};
        System.Console.WriteLine("Elements: \r\n");
        for(int index =0; index < intList.Count-1; index++)
        {
            System.Console.Write(intList[index].ToString());
            System.Console.Write(", ");
        }
        if(intList.Count > 1)
            System.Console.Write("and ");
        if(intList.Count > 0)
            System.Console.Write(intList[intList.Count-1]);     
        else
            System.Console.Write("<<Empty List>>");
    }
}

Upvotes: 1

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

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(); 

Upvotes: 5

Flydog57
Flydog57

Reputation: 7111

Sometimes brute force is the way to go. Consider something like this:

private string ConcatInts()
{
    List<int> intList = new List<int> {1, 2, 3, 4, 1};
    var buffer = new StringBuilder();
    var len = intList.Count;
    for (var i = 0; i < len; ++i)
    {
        if (i > 0 && i < len - 1)
        {
            buffer.Append(", ");
        }
        else if (i == len - 1)
        {
            buffer.Append(", and ");
        }
        buffer.Append(intList[i].ToString());
    }

    return buffer.ToString();
}

I usually don't like indexing into a List (I like to think of them as lists), but they do support indexing quite well.

Upvotes: 1

Related Questions