开发者

C# Last Element of List of List

This is probably a开发者_Python百科 really easy question, I want to access the last element of:

List<string>[] list = new List<string>[3];

So each list inside has 3 elements but how should I access the last of those lists?


You can use Enumerable.Last():

string lastElement = list.Last().Last();

The first call will return the last List<string>, and the second will return the last string within that list.

Alternatively, since you know the length of the array, you can access the list directly, and do:

string lastElement = list[2].Last();

If you know, in advance, that you're always going to have 3 lists with 3 elements, you might want to consider using a multidimensional array instead:

string[,] matrix = new string[3,3];

// fill it in..

string last = matrix[2,2];


If you have [[1,2,3],[4,5,6],[7,8,9]] and you want 9, use list.Last().Last(). If you want [3,6,9], use list.Select(sublist => sublist.Last()).


In C# 8.0 you can use the "hat" operator (^) to select an element from the end of a list.

The index from end operator ^, which specifies that an index is relative to the end of the sequence.

// get last item from last array
string last = list[^1][^1];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜