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.
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
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