,如果我有這樣的:C#列表清單?
List<List<int>> matrix = new List<List<int>>();
我將如何來填充它,所以它看起來是這樣的:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
,如果我有這樣的:C#列表清單?
List<List<int>> matrix = new List<List<int>>();
我將如何來填充它,所以它看起來是這樣的:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
首先,你會如何填充一個List<int>
以便它包含零?
你想組成一堆,然後將它們推入包含列表中。
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})});
阿爾尼斯L.這裏...
只是想補充一點,集合初始化器可以使用(如果NET 3.0支持):
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}};
你可能不想要使用矩陣表示列表,除非矩陣非常稀疏......但是如何編寫整數列表?那麼一旦你有其中一個,你會如何將它添加到你的列表清單?你需要多少次將這樣的列表添加到列表中?
如果您製作矩陣,爲什麼不使用two-dimensional array?
我真的會避免這種矩陣。沒有辦法確保每個子列表與其他列表的長度相同。如果它不是動態的,那麼你應該使用多維數組
int[,] names = new int[7,3];
而如果是稀疏的,可以考慮使用
int[][] matrix;
這是更爲高效的速度和內存佔用比使用列表。
如果你想要一些公開可讀的矩陣功能,你可以看看Math.Net's Iridium project。它支持稀疏矩陣,並且有大量的矩陣函數。 它的實現只比使用Double [,]稍慢,並且我已經將它用於超過60,000,000個值的矩陣上的函數。
不,它的效率並不高。每個List都有一些開銷,但是List類使用一個數組作爲內部存儲,所以差別並不大。 – Guffa 2009-12-04 01:05:59
這裏是初始化衣衫襤褸列表的一種方法:
matrix =
Enumerable.Repeat(0,3)
.Select(d => Enumerable.Repeat(0,7).ToList())
.ToList();
我會去的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);
}
如果你想在矩陣中放置其他值而不是「0」,只需替換添加到矩陣行的值即可。乾杯!
我不能拒絕問,爲什麼不使用BitVector?是否需要使用列表的列表來只有二進制序列?或者選擇了0和1; s爲例子目的?
http://msdn.microsoft.com/en-us/library/system.collections.specialized.bitvector32.aspx
你的意思是C#3.0,如集合初始化無關使用.NET 3.0。 – 2009-12-05 00:21:31