Reputation: 2026
This seems like a simple thing, but how do I address the elements of a nested List-of-Lists by index?
I recently shared a C# class that returned a List<List<int>>
with a colleague who didn't know how to address the resulting List<List<int>>
collection and couldn't find it on StackOverflow. find index of an int in a list describes how to index a List<int>
, but not how to address nested lists.
Upvotes: 2
Views: 8940
Reputation: 2026
Use an indexer to get the child list from the parent list, then use another indexer to get the actual item in the list. One may also use ElementAt
or other list functions, and foreach
or other iterators.
// create a jagged array for demo
List<List<int>> NestedListOfLists = (new List<int>[] {
(new int[] { 1, 2, 3 }).ToList(),
(new int[] { 4, 5 }).ToList(),
(new int[] { 6 }).ToList()
}).ToList();
// one way to address a List of Lists, returns 3:5:6
Console.WriteLine("{0}:{1}:{2}",
NestedListOfLists[0][2], // NestedListOfLists[0] returns the first list, which then can be indexed with [2] for the third element
NestedListOfLists[1][1], // NestedListOfLists[1] returns the first list, which is then indexed with [1]
NestedListOfLists[2][0] // NestedListOfLists[2] returns the first list, which is then indexed with [0]
);
/*Console.WriteLine("{0}",
NestedListOfLists[1,0] // this doesn't compile
);*/
// another way to address a List of Lists
Console.WriteLine("{0}",
(NestedListOfLists.ElementAt(0)).ElementAt(2) // NestedListOfLists.ElementAt(0) returns the first list, which then can be indexed with ElementAt(2) for the third element
);
// sometimes its practical to iterate through the lists
foreach( List<int> IntList in NestedListOfLists)
{
Console.Write("List of {0}: \t", IntList.Count() );
foreach (int i in IntList)
{
Console.Write("{0}\t", i );
}
Console.Write("\n");
}
Upvotes: 3