英文:
C# Create double[][] from DataTable
问题
我有一个DataTable,其中每一行和列中的每个条目都是双精度数。我需要将其转换为一个二维的double[][]
对象。没有列标题,行数和列数每次可能都不同。
是否有Linq可以简化这个过程?在构建double[][]
对象时,可以应用Math.Round()
来对每个值进行四舍五入吗?
英文:
I have a DataTable where every entry in every row and column is a double. I need to convert it to a two dimensional double[][]
object. There are no column headers and the number of rows and columns can be different each time.
Is there Linq to simplify this? Can I apply Math.Round()
for each value as I build my double[][] object?
答案1
得分: 1
我会使用这种高效且安全的方法:
DataColumn[] doubleColumns = dt.Columns.Cast<DataColumn>()
.Where(c => c.DataType == typeof(double))
.ToArray();
double[][] result = dt.AsEnumerable()
.Select(r => doubleColumns.Select(c => r.Field<double>(c)).ToArray())
.ToArray();
英文:
I'd use this approach that is efficient and safe:
DataColumn[] doubleColumns = dt.Columns.Cast<DataColumn>()
.Where(c => c.DataType == typeof(double))
.ToArray();
double[][] result = dt.AsEnumerable()
.Select(r => doubleColumns.Select(c => r.Field<double>(c)).ToArray())
.ToArray();
答案2
得分: 0
使用具有所有列都可以转换为double
的DataTable
(即列可以是float
,int
等类型)可以像这样放置:
using System.Linq;
...
DataTable table = ...
double[][] array = table
.Rows
.OfType<DataRow>()
.Select(dataRow => dataRow
.ItemArray
.Select(item => Convert.ToDouble(item))
.ToArray())
.ToArray();
当然,如果需要,您可以添加一些处理,例如Math.Round
;在内部的Select
之后添加它:
...
.Select(item => Convert.ToDouble(item)) // 从现在开始我们有double类型
.Select(value => Math.Round(value, 2)) // 让我们将值四舍五入
.ToArray())
...
英文:
Having DataTable
with all columns that can be converted into double
(i.e. columns can be of type float
, int
etc.) you can put something like this:
using System.Linq;
...
DataTable table = ...
double[][] array = table
.Rows
.OfType<DataRow>()
.Select(dataRow => dataRow
.ItemArray
.Select(item => Convert.ToDouble(item))
.ToArray())
.ToArray();
Sure, you can add some processing, say, Math.Round
if required; add it after the inner Select
:
...
.Select(item => Convert.ToDouble(item)) // from now on we have double
.Select(value => Math.Round(value, 2)) // Let's round the values
.ToArray())
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论