Creating a List in a C # List

If I have a 2+ list of int numbers, can I save these lists inside another list to pass it to another class or method? I want to have access to each list individually, but I want to be able to transfer them all together in one batch. What will be the syntax of this, as well as what will be the correct method of accessing each list in the main list. For example, I have these separate 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 }); 

Then I want to save them in another list in order to go to the method, for example:

 static public List<int> DoSomething (List<int> Allnums) { //My calculations } 

Then I want to save them back to the main list and return them to my main list.

+4
source share
6 answers

You can use the type List<List<int>> to store 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 } 
+10
source

That's quite possible:

 static public void DoSomething (List<List<int>> Allnums) { //My calculations } 

Note that there is no reason to return a List; the argument points to the original list of lists. First you will need to put all the lists in a list:

 List<List<int>> allLists = new List<List<int>>(); allLists.Add(Nums1); allLists.Add(Nums2); allLists.Add(Nums3); DoSomething(allLists); 
+1
source

It depends, as already indicated as awnser, you can use List<List<int>> . Although, since we use the OO language, and if the number of ints lists is the same every time, I would suggest an object.

Something like that:

 public class MyIntListObject { public List<int> Output1 {get;set;} public List<int> Output2 {get;set;} } 

to save lists. I would suggest it to maintain acceptability.

Youre method would turn into something like this:

 static public MyIntListObject DoSomething (List<int> Allnums) { //My calculations } 
+1
source
 static public List<int> DoSomething (List<int> Allnums) { //My calculations } 

it should be

 static public List<int> DoSomething (List<List <int>> Allnums) { //My calculations } 
0
source

what's wrong:

 Tuple<List<int>,List<int>> 
0
source
 //static public List<int> DoSomething (List<int> Allnums) DoSomething(Nums1.Concat(Nums2).Concat(Nums3).ToList()); 
0
source

Source: https://habr.com/ru/post/1385769/


All Articles