C# 从 DataTable 创建 double[][]

huangapple go评论69阅读模式
英文:

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&lt;DataColumn&gt;()
	.Where(c =&gt; c.DataType == typeof(double))
	.ToArray();

double[][] result = dt.AsEnumerable()
	.Select(r =&gt; doubleColumns.Select(c =&gt; r.Field&lt;double&gt;(c)).ToArray())
	.ToArray();

答案2

得分: 0

使用具有所有列都可以转换doubleDataTable(即列可以是floatint等类型)可以像这样放置:

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&lt;DataRow&gt;()
  .Select(dataRow =&gt; dataRow
    .ItemArray
    .Select(item =&gt; Convert.ToDouble(item))
    .ToArray())
  .ToArray();

Sure, you can add some processing, say, Math.Round if required; add it after the inner Select:

   ...
   .Select(item =&gt; Convert.ToDouble(item)) // from now on we have double
   .Select(value =&gt; Math.Round(value, 2))  // Let&#39;s round the values
   .ToArray())
   ...

huangapple
  • 本文由 发表于 2023年2月8日 23:50:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定