简体   繁体   English

如何获取字符串数组列表的最后一个元素?

[英]How can I grab the last element of a List of string arrays?

lstArray is a list of string arrays: lstArray是一个字符串数组列表:

List<string[]> lstArray = new List<string[]>();

Obviously its size varies. 显然它的大小各不相同。 In the sample below it has two elements; 在下面的示例中,它有两个元素; first one has 4, second one has 5 items in it. 第一个有4个,第二个有5个项目。 Last item always refers to a table name (tblPerson, tblCompany, etc.). 最后一项始终引用表名(tblPerson,tblCompany等)。 That's what I want to collect. 这就是我想收集的东西。 It might be 4th, 5th, or even 8th item sometimes. 有时可能是第4,第5或第8项。 I will have another list of string which is filled with these table names. 我将有另一个字符串列表,其中填充了这些表名称。

lstArray元素

lstArray[0]: lstArray [0]:

在此输入图像描述

lstArray 1 : lstArray 1

在此输入图像描述

If it's always the last element, you can use this: 如果它始终是最后一个元素,您可以使用:

var lastElements = lstArray.Select(e => e.Last());

If some of the arrays have zero elements, you might also use: 如果某些数组的元素为零,您还可以使用:

var lastElements = lstArray.Select(e => e.LastOrDefault());

In which case you could end up with some null entries. 在这种情况下,您最终可能会有一些null条目。 Another way to avoid that might be something like: 避免这种情况的另一种方法可能是:

var lastElements = lstArray.Select(e => e.Count == 0 ? string.Empty : e.Last());

This would give you string.Empty instead of null for empty arrays, which would be somewhat less error-prone for consuming code. 对于空数组,这将为您提供string.Empty而不是null ,这对于使用代码而言更不容易出错。

The following will return the last element on lstArray : 以下将返回lstArray上的最后一个元素:

var lastElement = lstArray.Last();

However what you want is the collection of all the last elements of the string arrays contained in lstArray , which you can obtain so: 但是你想要的是lstArray包含的字符串数组的所有最后元素的lstArray ,你可以这样获得:

var lastElements = lstArray.Select(i => i.Last())

do you mean something like this?: 你的意思是这样的吗?:

List<string[]> lstArray = new List<string[]>();
var result = lstArray.Select(a=>a.Last())
var lastElement = lstArray.Last().Last() //this will give the last element of last array

var lastElement = lstArray.Select(sublist => sublist.Last()); //this will give last element of each array in the list

Get the List last item 获取列表最后一项

int len = strList.length();
String strArr[] = strList.get(len);

Get String Array last element ie last string 获取String Array最后一个元素即最后一个字符串

String str = strArr[strArr.size()-1]

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

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