C# 从 DataTable 创建 double[][]

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

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

我会使用这种高效且安全的方法:

  1. DataColumn[] doubleColumns = dt.Columns.Cast<DataColumn>()
  2. .Where(c => c.DataType == typeof(double))
  3. .ToArray();
  4. double[][] result = dt.AsEnumerable()
  5. .Select(r => doubleColumns.Select(c => r.Field<double>(c)).ToArray())
  6. .ToArray();
英文:

I'd use this approach that is efficient and safe:

  1. DataColumn[] doubleColumns = dt.Columns.Cast&lt;DataColumn&gt;()
  2. .Where(c =&gt; c.DataType == typeof(double))
  3. .ToArray();
  4. double[][] result = dt.AsEnumerable()
  5. .Select(r =&gt; doubleColumns.Select(c =&gt; r.Field&lt;double&gt;(c)).ToArray())
  6. .ToArray();

答案2

得分: 0

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

  1. using System.Linq;
  2. ...
  3. DataTable table = ...
  4. double[][] array = table
  5. .Rows
  6. .OfType<DataRow>()
  7. .Select(dataRow => dataRow
  8. .ItemArray
  9. .Select(item => Convert.ToDouble(item))
  10. .ToArray())
  11. .ToArray();

当然,如果需要,您可以添加一些处理,例如Math.Round;在内部的Select之后添加它:

  1. ...
  2. .Select(item => Convert.ToDouble(item)) // 从现在开始我们有double类型
  3. .Select(value => Math.Round(value, 2)) // 让我们将值四舍五入
  4. .ToArray())
  5. ...
英文:

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:

  1. using System.Linq;
  2. ...
  3. DataTable table = ...
  4. double[][] array = table
  5. .Rows
  6. .OfType&lt;DataRow&gt;()
  7. .Select(dataRow =&gt; dataRow
  8. .ItemArray
  9. .Select(item =&gt; Convert.ToDouble(item))
  10. .ToArray())
  11. .ToArray();

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

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

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:

确定