我List<string>喜欢:
List<String> lsRelation = new List<String>{"99","86","111","105"}.
Run Code Online (Sandbox Code Playgroud)
现在我想找到数字111,它是倒数第二个字符串.
所以我试过了:
String strSecondLast=lsrelation.Last() - 2;
Run Code Online (Sandbox Code Playgroud)
这不起作用.那么我怎样才能找到List的倒数第二个元素Last().
小智 12
使用:
if (lsRelation.Count >= 2)
secLast = lsRelation[lsRelation.Count - 2];
Run Code Online (Sandbox Code Playgroud)
如果你知道这是一个IList<T>有索引器:
string secondLast = null;
if (lsRelation.Count >= 2)
secondLast = lsRelation[lsRelation.Count - 2];
Run Code Online (Sandbox Code Playgroud)
您可以创建一个扩展名,如:
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样使用它:
string secondLast = lsRelation.SecondLast();
Run Code Online (Sandbox Code Playgroud)
从C# 8.0开始,您可以使用Index访问相对于序列末尾的元素:
if (lsRelation.Count >= 2)
secLast = lsRelation[^2];
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅文档
这样做有很多选择.只提一个我还没有见过的人:
List<string> lsRelation = new List<String>{"99","86","111","105"};
String strSecondLast = lsRelation.Skip(lsRelation.Count() - 2).First();
Run Code Online (Sandbox Code Playgroud)
你可以使用ElementAt(list.Count - 2):
List<String> lsRelation = new List<String> { "99", "86", "111", "105" };
Console.WriteLine(lsRelation.ElementAt(lsRelation.Count - 2)); // 111
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14770 次 |
| 最近记录: |