Steve Wellens

Programming in the .Net environment

Sponsors

Links

Nested Generic Lists? Cool!

While answering a question on the Asp.Net forums, I was pleasantly surprised to find nested Generic Lists are possible. They seem much easier than multidimensional arrays.

Here is the key line:     List<List<int>> MyListOfIntLists; 

    protected void Button1_Click(object sender, EventArgs e)
    {
        List<int> MyInts1;
        List<int> MyInts2;
 
        List<List<int>> MyListOfIntLists;
 
        // create the list of lists
        MyListOfIntLists = new List<List<int>>();
 
        MyInts1 = new List<int>();
        MyInts1.Add(1);
        MyInts1.Add(2);
        MyInts1.Add(3);
 
        MyInts2 = new List<int>();
        MyInts2.Add(4);
        MyInts2.Add(5);
        MyInts2.Add(6);
 
        MyListOfIntLists.Add(MyInts1);
        MyListOfIntLists.Add(MyInts2);
 
        // access the list of lists
        MyInts1 = MyListOfIntLists[0];
        MyInts2 = MyListOfIntLists[1];
    }

 

I hope you find this useful.

Steve Wellens

Posted: Oct 26 2008, 02:03 PM by SGWellens | with 6 comment(s) |
Filed under: , ,

Comments

yaronn01 said:

I also use them sometimes but I also think that too much generics in code makes it somehow less readable, not really sure why.

# October 28, 2008 6:25 PM

Fabrice Marguerie said:

Do you know that you can also use the following syntax?

List<List<int>> MyListOfIntLists;

myListOfIntLists = new List<List<int>> {

 new List<int> { 1, 2, 3 },

 new List<int> { 4, 5, 6 },

};

or

var myListOfIntLists = new List<List<int>> {

 new List<int> { 1, 2, 3 },

 new List<int> { 4, 5, 6 },

};

This is called collection initializers.

# October 28, 2008 6:48 PM

Ramon Smits said:

You mention multidimensional arrays but you probably ment jagged arrays.

So not:

  int[,] data; // Multidimentional

But:

  int[][] data; // Jagged

# October 29, 2008 5:23 AM

SGWellens said:

@Ramon,

The phrase 'Multidimensional arrays' include both Jagged and Rectangular arrays.  But I agree the term Jagged is more specific.

# October 29, 2008 8:51 AM

syed.tayyab.ali said:

By chance I got your weblog, and find this beautiful post.

# December 8, 2008 1:18 PM

SGWellens said:

That's very nice of you to say. Thank you.

# December 8, 2008 1:38 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)