tags:

views:

65

answers:

2

This is probably a 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?

+4  A: 

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];
Reed Copsey
Ok, cool, but is there a way to get the index number because I want to access all three of those elements in the last list.
MCH
like list[0][lastList], list[1][lastList], list[2][lastList]
MCH
@MCH: you can do list[0].Last(), list[1].Last(), etc... Is that what you want?
Reed Copsey
Assuming .Net 3.5+, for earlier versions of the framework, `list[3][list[3].Count - 1]` will do same.
Will A
@MCH: or, alternatively, if you want a list of all of the last elements, you can do: list.Select(l => l.Last()).ToList();
Reed Copsey
@Will A: (should be list[2] - it's only 3 elements long)
Reed Copsey
yeah, that's it, thanks!
MCH
@Reed - D'oh - good point - that's coming from a VB.Net background for you. :)
Will A
Thanks for all the help guys. I am still very new to dot net and I am working on learning WPF, so even a few simple things have tripped me up.
MCH
+3  A: 

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

strager