简体   繁体   中英

C# list of list?

If i have this:

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

how would I populate it so it looks something like this:

0 0 0 0 0 0 0 

0 0 0 0 0 0 0

0 0 0 0 0 0 0
List<List<int>> matrix = new List<List<int>>(new []{
                 new List<int>(new []{0, 0, 0, 0, 0, 0, 0}),
                 new List<int>(new []{0, 0, 0, 0, 0, 0, 0}),
                 new List<int>(new []{0, 0, 0, 0, 0, 0, 0})});

Arnis L. here...

Just wanted to add that collection initializers might be used (if .Net 3.0 is supported):

var matrix = new List<List<int>>{
                 new List<int>{0, 0, 0, 0, 0, 0, 0},
                 new List<int>{0, 0, 0, 0, 0, 0, 0},
                 new List<int>{0, 0, 0, 0, 0, 0, 0}};

First of all, how would you populate a single List<int> so that it contains zeroes?

You want to make up a bunch of those and then push them into the containing list.

I really would avoid this for matrices. There is no way of ensuring that each sub list is the same length as the others. If its not dynamic then you should use multidimensional arrays

int[,] names = new int[7,3];

如果要制作矩阵,为什么不使用二维数组呢?

Here is one way to initialise the ragged list:

matrix =
  Enumerable.Repeat(0,3)
  .Select(d => Enumerable.Repeat(0,7).ToList())
  .ToList();

You might not want to use lists for a matrix representation unless the matrix is really sparse...but how would you make a list of ints? Then once you had one of those, how would you add that to your list of lists? How many times do you need to add such lists to your list?

And if it is sparse, consider using

int[][] matrix;

This is far more efficient in speed and memory footprint than using a List.

If you want some openly readable matrix functionality you might look at Math.Net's Iridium project . It supports sparse matrixes, and has a huge number of matrix functions. Its implementation is only slightly slower than using Double[,], and I've used it for functions on matrixes with over 60,000,000 values.

我会选择int[,]因为它对我来说更具可读性,至少对我来说...

int rows;
int columns;
List<List<int>> matrix;

matrix = new List<List<int>>();
for (int i = 0; i < rows; i++)
{
    List<int> row;

    row = new List<int>();
    for (int j = 0; j < columns; j++)
    {
        row.Add(0);
    }

    matrix.Add(row);
}

If you want to place something else instead of "0" in the matrix, just replace the value that is added to the matrix row. Cheers!

i couldnt resist from asking, why dont you use a BitVector? is there a need to use list of list to have just binary sequences? or have chosen 0's and 1;s for example purpose?

http://msdn.microsoft.com/en-us/library/system.collections.specialized.bitvector32.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM