查找列表< T>倒数第二个元素 [英] Find List<T> second to last element

查看:91
本文介绍了查找列表< T>倒数第二个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在列表中找到倒数第二个项目。一篇文章提出了我使用的搜索词,他们建议获取最后一个元素的索引,然后备份一个步骤。这真的是这样做的方法吗?似乎有点糊涂/硬编码。也许我太偏执了??

I would like to find the second to the last item in a list. One article came up with the search terms I used and they suggested getting the index of the last element then backing up one step. Is this really the way to do it....? Seems kinda kludgy / hard coded. Perhaps I'm being too paranoid??

int _lstItemIdx = List<MyObj>.IndexOf(List<MyObj>.Last());
int _sndLstItmIdx = (_lstItemIdx - 1);

谢谢

推荐答案

出什么问题了:

var result = myList[myList.Count-2];

当然,如果您的列表中没有2个元素,则需要适当的异常处理。

Of course, you need appropriate exception handling in case your list doesn't have 2 elements.

您可以将其转换为扩展方法:

And you can turn it into an extension method:

public static T SecondToLast<T>(this IList<T> source)
{
    if (source.Count < 2)
        throw new ArgumentException("The list does not have at least 2 elements");

    return source[source.Count - 2];
}

这篇关于查找列表&lt; T&gt;倒数第二个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆