Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list within a list C#

Tags:

c#

list

If I have 2+ lists of int numbers is there a way I can store those lists inside another list to pass it to another class or method? I want to be able to access each list individually, but I want to be able to pass them all together in one batch. What would be the syntax this and also what would be the proper method of accessing each list within the master list. Example, I have these individual lists:

List<int> Nums1= new List<int>(new int[] { 6, 76, 5, 5, 6 });
List<int> Nums2= new List<int>(new int[] { 6, 4, 7, 5, 9 });
List<int> Nums3= new List<int>(new int[] { 22, 11, 5, 4, 6 });

I want to then store these in another list to pass to a method such as:

static public List<int> DoSomething (List<int> Allnums)
{

//My calculations

}

Then I want to be able to store them back into a master list and return them to my main.

like image 487
Emerica. Avatar asked Dec 16 '22 06:12

Emerica.


2 Answers

You can use a List<List<int>> type to hold a list of lists.

List<List<int>> allNums = new List<List<int>>();

allNums.Add(Nums1);
allNums.Add(Nums2);
allNums.Add(Nums3);

DoSomething(allNums);

//elsewhere
static public List<int> DoSomething (List<List<int>> Allnums)
{

//My calculations

}

With later versions of C# (I believe C# 6 and onwards) you can use collection initializer notation:

var allNums = new List<List<int>>{ Nums1, Nums2, Nums3 };
like image 61
Oded Avatar answered Dec 22 '22 01:12

Oded


This is perfectly possible:

static public void DoSomething (List<List<int>> Allnums)
{

//My calculations

}

Notice that there is no reason to return a List; the argument points to the original list of lists. You'd have to put all the lists in a list first though:

List<List<int>> allLists = new List<List<int>>();
allLists.Add(Nums1);
allLists.Add(Nums2);
allLists.Add(Nums3);

DoSomething(allLists);
like image 20
Emond Avatar answered Dec 22 '22 00:12

Emond