20

I have some code written in C#. In this code, I have a List<KeyValuePair<int, string>> items. I am trying to get the second-to-last item in the list. I'm having problems doing it though.

Originally, my collection was just a Dictionary<int, string>. At that point, I was using:

var nextToLast = items.Reverse().Skip(1).FirstOrDefault();

That worked. However, since items is now a List<KeyValuePair<int, string>>, the Reverse method returns a void. So, I can't do the skip.

Anyone know of an elegant way for me to get the second-to-last item from a List<KeyValuePair<int, string>> in C#?

I know I can use a loop. I just figured there had to be a better way.

1
  • use OrderBy or OrderByDescending on your list
    – techspider
    Jun 15, 2016 at 16:45

5 Answers 5

40

You have a List<>, so why not use its Count and indexer properties:

var item = items[items.Count-2];

Make sure that there are at least two items in the list though.

2
  • 6
    Thanks. Boy do I feel dumb. I was so focused on using LINQ that I totally overlooked the obvious. Thanks again.
    – user70192
    Jun 15, 2016 at 17:12
  • This doesn't handle the list having 0 or 1 items. The LINQ solution returns an empty IEnumerable.
    – Ryan
    May 7, 2021 at 8:40
28

Starting with C# 8.0 you can use the ^ operator, which gives you access to the index from the end[1].

So you can just do:

var item = items[^2];

More examples:

int[] xs = new[] { 0, 10, 20, 30, 40 };
int last = xs[^1];
Console.WriteLine(last);  // output: 40

var lines = new List<string> { "one", "two", "three", "four" };
string prelast = lines[^2];
Console.WriteLine(prelast);  // output: three

string word = "Twenty";
Index toFirst = ^word.Length;
char first = word[toFirst];
Console.WriteLine(first);  // output: T
24

Try this :

items.AsEnumerable().Reverse().Skip(1).FirstOrDefault();
2
  • 1
    using this, doesn't the OP risk the following problem : Possible multiple enumeration of IEnumerable? Because of the AsEnumerable ? That could lead to unwanted memory leaks. Jun 15, 2016 at 16:55
  • 4
    @KevinAvignon The AsEnumerable() essentially returns the IEnumerable interface of the List, which allows us to calls the extension method Enumerable.Reverse() instead of void List.Reverse(). There is no chance of multiple enumeration. This is because the IEnumerable was never exposed, as we are returning a T (or, more specifically, a KeyValuePair<int, string>).
    – Xiaoy312
    Jun 15, 2016 at 17:04
9

You can use ElementAtOrDefault

items.ElementAtOrDefault(items.Count - 2) 

Or Take and LastOrDefault

items.Take(items.Length - 1).LastOrDefault();
7
  • 1
    Needs second to last - so -2
    – PaulF
    Jun 15, 2016 at 16:49
  • @PaulF Thanks. Changed it to -2 :)
    – Valentin
    Jun 15, 2016 at 16:50
  • I think the second method is preferable as there is no need to check for at least 2 elements in the array. The first will cause an exception without a check.
    – PaulF
    Jun 15, 2016 at 16:58
  • 1
    You might want to use ElementAtOrDefault just to be safe.
    – Xiaoy312
    Jun 15, 2016 at 17:06
  • 1
    @Xiaoy312 Thanks. ElementAtOrDefault suits better
    – Valentin
    Jun 15, 2016 at 17:09
1
        public IList<string> newList = new List<string>();
    public void OnGet()
    {
        var list = new List<string> { "one", "two", "three", "four" };
        list.RemoveAt(0);
        while (list.Count != 0)
        {
            var index = list.Next(0, list.Count);
            newlist.Add(list[index]);
            list.RemoveAt(index);
        }
    }

<tr>
<td>
@Model.newList[0]
<td>
<br />
<td>
@Model.newList[1]
<td>
<br />
<td>
@Model.newList[2]
<td>
<br />
</tr>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.