Click here to Skip to main content
15,885,704 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,I want to have a two dimensional array which elements are lists.
List<int>[,] dMinMax = new List<int>[3,1000];

now I want to fill the array in a for clause.for example:
dMinMax[1, 2] .Add(3);

but It gives me the error "Object reference not set to an instance of an object." on the above line.I think it means that I should build the list at first but Can I build 1000 lists? Is there a better solution? If there is no other way ,how can I build them?
Posted

Your line List<int>[,] dMinMax = new List<int>[3,1000];</int></int> creates an array of list objects, which basically allocates pointer space in the array, nothing more. Then your line dMinMax[1, 2].Add(3); tries to add an item to a list that has not yet been created. In other words, if you debug you'll find that dMinMax[1, 2] is null.

Try inserting dMinMax[1, 2] = new List<int>();</int> to actually create the list before you try to add an item to it.
 
Share this answer
 
Comments
ready to learn 29-Feb-12 15:35pm    
great.That's exactly wat I wanted.
A List is like an array, but it does not directly support multiple dimensions. To overcome this, you can create a List of Lists, like this:

C#
var list = new List<List<int>>();
for(int i = 0; i < 10; ++i) {
    var innerList = new List<int>();
    list.Add(innerList);
}
 
Share this answer
 
Comments
ready to learn 29-Feb-12 13:51pm    
What about creating list of list of list? and how can I access to a special element?
[no name] 29-Feb-12 14:09pm    
You can use the same technique to nest the List any level deep. To access an element. Check this link: http://www.dotnetperls.com/nested-list
Dr.Walt Fair, PE 29-Feb-12 15:00pm    
Multiple dimension array s are fine in C#. Please don't give wrong information.
[no name] 29-Feb-12 22:29pm    
Yes, they're fine. But the OP wants to know about nested lists, which are fine too. I don't see any problem using them.
Not sure but may be Tuple will work here:

C#
List<Tuple<int, int>> list = new List<Tuple<int, int>>();


Adding items:

C#
list.Add(new Tuple<int,int>(1, 1));
 
Share this answer
 
v3
Comments
Dr.Walt Fair, PE 29-Feb-12 15:01pm    
Multidimensional arrays work fine. He just forgot to initialize the List<int>.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900