简体   繁体   中英

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

lstArray is a list of string arrays:

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. Last item always refers to a table name (tblPerson, tblCompany, etc.). That's what I want to collect. It might be 4th, 5th, or even 8th item sometimes. I will have another list of string which is filled with these table names.

lstArray元素

lstArray[0]:

在此输入图像描述

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

The following will return the last element on 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:

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 str = strArr[strArr.size()-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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