Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of List<int> in C#?

Tags:

arrays

c#

.net

list

I have a problem where I need an array of arrayList.

For example if we take an Array of ArrayList of int, it will be like:

int[]<List> myData = new int[2]<List>;

myData[0] = new List<int>();
myData[0].Add(1);
myData[0].Add(2);
myData[0].Add(3);


myData[1] = new List<int>();
myData[1].Add(4);
myData[1].Add(5);
myData[1].Add(6);

myData[0].Add(7);

How can we implement a datastructure like the above in C#?

In C, its like a array of LinkedList. How can I do the same in C#?

like image 656
sandyiit Avatar asked Feb 01 '11 15:02

sandyiit


People also ask

How to create an array of lists in C #?

This tutorial will discuss the methods to create an array of lists in C#. The List<T> [] notation can be used to declare an array of lists of type T in C#. Keep in mind that this will only declare an array of null references.

How to declare an array of lists of type T in C?

The List<T> [] notation can be used to declare an array of lists of type T in C#. Keep in mind that this will only declare an array of null references.

How to use List<int> in an array of lists?

You'll need to put a new List<int> () into each slot of the array before using it. However, you should probably use a List<List<int>> instead of an array of lists. Thanks for contributing an answer to Stack Overflow!

What is an array in C++?

An array is a collection of data that holds fixed number of values of same type. For example: if you want to store marks of 100 students, you can create an array for it. float marks[100]; The size and type of arrays cannot be changed after its declaration.


2 Answers

var myData = new List<int>[]
{
    new List<int> { 1, 2, 3 },
    new List<int> { 4, 5, 6 }
};
like image 117
QrystaL Avatar answered Oct 11 '22 23:10

QrystaL


Almost as you tried, only the first line is incorrect:

List<int>[] myData = new List<int>[2];
myData[0] = new List<int>();
myData[0].Add(1);
myData[0].Add(2);
myData[0].Add(3);


myData[1] = new List<int>();
myData[1].Add(4);
myData[1].Add(5);
myData[1].Add(6);

myData[0].Add(7);

Thanks to madmik3, here is a link you can read something about generic lists in C#: click me

Also, if you want to read something about arrays, e.g. the static copy method of the Array class, here is some link for that.

like image 35
Sören Avatar answered Oct 11 '22 22:10

Sören