我正在尝试从csv文件中将数字列表读入数组,因为我希望能够将这些数字的所有可能组合输出到文件。
例如,这里是CSV文件中的数字列表
-8,-13,-8,-2,-4,6,4
-6,-12,-5,3,3,12,5
-5,-9,-4,5,10,13,10
-4,-8,-2,7,13,17,11
-3,-6,0,8,14,18,13
-2,-5,2,9,15,22,17
-1,-3,5,10,16,23,18
如何将单独数组中列表中的第一个数字读取到列表中的下一个数字等等?
这是使用visual basic
由于
答案 0 :(得分:1)
如果您的文件由7个数字组成的行组成,那么您需要7个不同的集合变量。因为您没有指定存在多少行,所以我假设行数未知,因此要使用的首选集合类型是List(Of Integer)而不是数组。这是因为List并不需要事先知道你需要在其中存储多少元素
Dim col1 As List(Of Integer) = new List(Of Integer)
Dim col2 As List(Of Integer) = new List(Of Integer)
Dim col3 As List(Of Integer) = new List(Of Integer)
Dim col4 As List(Of Integer) = new List(Of Integer)
Dim col5 As List(Of Integer) = new List(Of Integer)
Dim col6 As List(Of Integer) = new List(Of Integer)
Dim col7 As List(Of Integer) = new List(Of Integer)
for each line in File.ReadLines("c:\temp\this_is_your_file_to_read.csv")
Dim parts = line.Split(","c)
if parts.Length = 7 Then
Col1.Add(Convert.ToInt32(parts(0)))
Col2.Add(Convert.ToInt32(parts(1)))
Col3.Add(Convert.ToInt32(parts(2)))
Col4.Add(Convert.ToInt32(parts(3)))
Col5.Add(Convert.ToInt32(parts(4)))
Col6.Add(Convert.ToInt32(parts(5)))
Col7.Add(Convert.ToInt32(parts(6)))
Else
MessageBox.Show("Line not matching the expected pattern")
End If
Next
答案 1 :(得分:0)
在Excel中,您可以使用build in mechanizm" Menu \ Data \ Text to column"。您可以指定komma将其分隔为列。
或者,如果您不想使用Excel,则应使用" open file for"读取数据的方法,ald使用split()函数将数字赋予dim数组。
答案 2 :(得分:0)
除了Steve的回答,我还提供了一个更通用的多维数组方法。这是因为我们可以将输入csv视为一种矩阵。
Dim lines = File.ReadAllLines("E:\\MAtrix.csv")
Dim matrixHeight = lines.Length - 1
Dim matrixWidth = lines(0).Split(",").Length - 1 'Assume all lines have same length
Dim matrix(,) As Integer = New Integer(matrixHeight, matrixWidth) {}
'Go thru all lines of file
For x As Integer = 0 To matrixHeight
Dim csv = lines(x).Split(",")
'Go thru all csv of the line
For y As Integer = 0 To matrixWidth
matrix(x, y) = csv(y) 'e.g. [0,0] => -8
Next
Next
'Test
For x As Integer = 0 To matrix.GetUpperBound(0)
For y As Integer = 0 To matrix.GetUpperBound(1)
Console.Write("[{0},{1}] => {2}; ", x, y, matrix(x, y).ToString())
Next
Console.WriteLine()
Next
打印:
'[0,0] => -8; [0,1] => -13; [0,2] => -8; [0,3] => -2; [0,4] => -4; [0,5] => 6; [0,6] => 4;
'[1,0] => -6; [1,1] => -12; [1,2] => -5; [1,3] => 3; [1,4] => 3; [1,5] => 12; [1,6] => 5;
'[2,0] => -5; [2,1] => -9; [2,2] => -4; [2,3] => 5; [2,4] => 10; [2,5] => 13; [2,6] => 10;
'[3,0] => -4; [3,1] => -8; [3,2] => -2; [3,3] => 7; [3,4] => 13; [3,5] => 17; [3,6] => 11;
'[4,0] => -3; [4,1] => -6; [4,2] => 0; [4,3] => 8; [4,4] => 14; [4,5] => 18; [4,6] => 13;
'[5,0] => -2; [5,1] => -5; [5,2] => 2; [5,3] => 9; [5,4] => 15; [5,5] => 22; [5,6] => 17;
'[6,0] => -1; [6,1] => -3; [6,2] => 5; [6,3] => 10; [6,4] => 16; [6,5] => 23; [6,6] => 18;