如何将数据表转换为c#wpf中双精度的矩阵[] []? [英] How do i convert a datatable to a matrix[][] of doubles in c# wpf?
问题描述
我正在尝试将dataTable转换为双精度矩阵[] []但没有成功。
我有一个dataTable,例如: 20列100行。我想将值从2列提取到最后一列,并将其存储到双精度矩阵[] []中。
我尝试了什么:
I'm trying to convert a dataTable to a matrix [][] of doubles with no success.
I have a dataTable with e.g. 20 columns and 100 rows. I want to extract the values from the 2 column to the last column and store this into a matrix[][] of doubles.
What I have tried:
public double[][] ConvertDataTableToMatrix(DataTable dt)
{
double[][] matrix = new double[dt.Rows.Count][];
//start from second row as ColumnNames are stored in first row
for (int row = 1; row < dt.Rows.Count + 1; row++)
{
for (int col = 1; col < dt.Columns.Count; col++)
{
matrix[row] = Convert.ToDouble(dt.Rows[row - 1][col]);
}
}
return matrix;
}
推荐答案
尝试这样的事情:
Try something like this:
public double[][] ConvertDataTableToMatrix(DataTable dt)
{
double[][] matrix = new double[dt.Rows.Count][];
Converter<object, double> converter = Convert.ToDouble;
for (int row = 0; row < dt.Rows.Count; row++)
{
matrix[row] = Array.ConvertAll(dt.Rows[row].ItemArray, converter);
}
return matrix;
}
DataRow.ItemArray属性(System.Data) [ ^ ]
编辑: ItemArray
返回对象
的数组,需要将其转换为<$的数组C $ C>双。最简单的方法是使用 Array.ConvertAll
方法 [ ^ ]。
注意:您的代码中的注释不会感。你说你从第二行开始,但你的循环从 1
到 Rows.Count
包括在内,并且然后使用 row - 1
作为循环中的索引器。因此,您将遍历所有行,包括第一行。
DataRow.ItemArray Property (System.Data)[^]
ItemArray
returns an array of object
, which needs to be converted to an array of double
. The easiest way to do that is to use the Array.ConvertAll
method[^].
NB: The comment in your code makes no sense. You say you're starting from the second row, but your loop runs from 1
to Rows.Count
inclusive, and you then use row - 1
as the indexer within the loop. As a result, you're looping over all of the rows, including the first one.
这篇关于如何将数据表转换为c#wpf中双精度的矩阵[] []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!