简体   繁体   English

使用LINQ将DataTable转换为object [,]数组

[英]Convert DataTable into object[ , ] array with LINQ

I sincerely apologize if this has been asked before; 真心的道歉,我真心的道歉。 maybe I am just blind and not finding it. 也许我只是盲目的而没有找到它。 Is it possible to convert a DataTable into an object[ , ] type array using LINQ? 是否可以使用LINQ将DataTable转换为object [,]类型的数组? Using the following code I can convert it into object[][] but that's not what I need unfortunately: 使用以下代码,我可以将其转换为object [] [],但是不幸的是,这不是我所需要的:

object[][] tableEnumerable = dtReportData.AsEnumerable().Select(x => x.ItemArray).ToArray();

What I need is: 我需要的是:

object [,] = ....?

Thank you in advance for any help and again, I apologize if this is a duplicate post. 预先感谢您的帮助,如果这是重复的帖子,我再次表示歉意。

EDIT: I do not want object[][] as the posted solution is referring to, I need object[,]. 编辑:我不希望object [] []作为发布的解决方案所指,我需要object [,]。 At least learn to read people before you start subtracting points. 至少在开始减分之前先学会阅读。

You cannot use Linq to create a rectangular array - Linq only operates on single-dimension arrays. 您不能使用Linq创建矩形数组-Linq仅在单维数组上运行。 You will need to use traditional for loops: 您将需要使用传统的for循环:

object[,] objectArray = new object[dtReportData.Rows.Count,
                                   dataTable1.Columns.Count];

for(int row = 0; row < dtReportData.Rows.Count; row++)
{
  for(int col = 0; col < dtReportData.Columns.Count; col++)
  {
    objectArray[row, col] = dtReportData.Rows[row][col];
  }
}

You could make this an extension method of DataTable to make the syntax cleaner if you like: 如果愿意,可以将其设为DataTable的扩展方法,以使语法更简洁:

object[][] tableEnumerable = dtReportData.ToRectangularArray()

The extension method would be something like: 扩展方法将类似于:

public static class MyDataTableExtensions
{
   public static object[,] ToRectangularArray(this DataTable dt)
   {
       // code above goes here
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM