简体   繁体   English

如何从列表中查找倒数第二个元素?

[英]How to find second last element from a List?

I have a List<string> like:我有一个List<string>像:

 List<String> lsRelation = new List<String>{"99","86","111","105"}.

Now i want to find the Number 111 that is the second to last string.现在我想找到倒数第二个字符串的数字 111。

So I have tried:所以我尝试过:

String strSecondLast=lsrelation.Last() - 2;

which doesn't work.这是行不通的。 So how can i find the second to last element of a List using Last() .那么如何使用Last()找到 List 的倒数第二个元素。

Use:用:

if (lsRelation.Count >= 2)
    secLast = lsRelation[lsRelation.Count - 2];

If you know that's an IList<T> which has an indexer:如果你知道这是一个IList<T> ,它有一个索引器:

string secondLast = null;
if (lsRelation.Count >= 2)
    secondLast = lsRelation[lsRelation.Count - 2];

You could create an extension like:您可以创建一个扩展,如:

public static T SecondLast<T>(this IEnumerable<T> items)
{
    if (items == null) throw new ArgumentNullException("items");
    IList<T> list = items as IList<T>;
    if (list != null)
    {
        int count = list.Count;
        if (count > 1)
        {
            return list[count - 2];
        }
        else
            throw new ArgumentException("Sequence must contain at least two elements.", "items");
    }
    else
    {
        try
        {
            return items.Reverse().Skip(1).First();
        } catch (InvalidOperationException)
        {
            throw new ArgumentException("Sequence must contain at least two elements.", "items");
        }
    }
}

Then you can use it in this way:然后你可以这样使用它:

string secondLast = lsRelation.SecondLast();

Starting with C# 8.0 you can use Index to get access to elements relative to the end of sequence:C# 8.0开始,您可以使用Index访问与序列末尾相关的元素:

if (lsRelation.Count >= 2)
    secLast = lsRelation[^2];

See docs for more information有关更多信息,请参阅文档

You can use ElementAt(list.Count - 2) :您可以使用ElementAt(list.Count - 2)

List<String> lsRelation = new List<String> { "99", "86", "111", "105" };
Console.WriteLine(lsRelation.ElementAt(lsRelation.Count - 2)); // 111

There are lots of options for doing this.有很多选择可以做到这一点。 Just to mention one that I've not seen here yet:只是提一个我还没有在这里看到的:

List<string> lsRelation = new List<String>{"99","86","111","105"};
String strSecondLast = lsRelation.Skip(lsRelation.Count() - 2).First();

You can't do this using Last() .你不能使用Last()来做到这一点。 Try this.尝试这个。 You take the length of the list and subtract 2:您取列表的长度并减去 2:

if (lsRelation.Count >= 2)
{
    var item = lsRelation[lsRelation.Count - 2];
}

Edit:编辑:

Based on the comment, here's an example using the Last() method, which would be ridiculous to use:根据评论,这是一个使用Last()方法的示例,使用起来很荒谬:

if (lsRelation.Count >= 2)
{
    var item = lsRelation.Last(x => x == lsRelation[lsRelation.Count - 2]);
}

Ambiguous question - what if your list has only one element?模棱两可的问题 - 如果您的列表只有一个元素怎么办? what if your list is empty?如果你的列表是空的怎么办? what if your list is null?如果您的列表是 null 怎么办?

the obvious answer to a List would be List的明显答案是

var beforeLast = lsRelation[lsRelation.Count -2];

to cover all your edge cases, I would use为了涵盖所有边缘情况,我会使用

string beforeLast = null;
if (lsRelation != null && lsRelation.Count > 1)
   beforeLast = lsRelation[lsRelation.Count - 2];

if it's an IEnumerable<string> ,如果它是IEnumerable<string>

string beforeLast = null;
if (lsRelation != null) {
  int l_count = lsRelation.Count();
  if (l_count > 1)
     beforeLast = lsRelation.Skip(l_count - 2).Take(1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM