Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Get Second to Last Item in a List

Tags:

c#

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.

like image 657
user70192 Avatar asked Jun 15 '16 16:06

user70192


1 Answers

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
like image 106
Dekel Avatar answered Sep 21 '22 15:09

Dekel