如何将 DataTable.Select() 的结果传递给一个新的 DataTable?

34

我有一个名为 dt2DataTable,其中包含一些数据。我正在调用它的 Select 方法来获取特定行。

DataRow[] foundRows;

expression = "parent_id=1";

foundRows = dt2.Select(expression);

我该如何将 Select 方法的结果传递给一个新的 DataTable – 比如说 FilteredData
3个回答

69

你可以使用CopyToDataTable,该方法可用于IEnumerable<DataRow>类型。

var filteredData = dt2.Select(expression).CopyToDataTable();

19

为了澄清一下,Select 方法返回一个类型为 DataRow 的数组。这就是为什么我们需要使用 CopyToDataTable() 的原因。Alex的回答很好。但是,如果 Select 没有返回任何行,CopyToDataTable() 将抛出 InvalidOperationException

因此,在使用 CopyToDataTable() 之前,请检查至少存在一行 DataRow

var filteredDataRows = dt2.Select(expression);

var filteredDataTable = new DataTable();

if(filteredDataRows.Length != 0)
    filteredDataTable = filteredDataRows.CopyToDataTable();

为什么要使用 var filteredDataRows 而不是 DataTable[] filteredDataRows?你的解决方案很好,我只是好奇。 - Dave Hampel
@DaveHampel 当你有点懒或者为了更好地监督代码时,请使用 var,变量名称对齐。这意味着相同且编译结果相同,确实是强类型的。只是不够明确。当赋值显而易见时,我通常使用 var。我不会写 DataTable table = New DataTable(); 但我会使用 MyFancyClass mfc = SomeFunctionReturningAnMFC()。更多信息请参见 https://intellitect.com/when-to-use-and-not-use-var-in-c/ 和 https://dev59.com/f2445IYBdhLWcg3wapvF#4868500。 - SvendK

16

为什么不使用 DataView 呢?

DataView view = new DataView(dt2);
view.RowFilter = "parent_id = 1";

DataView 的行为与一个 DataTable 基本一致,但是有一个额外的好处:底层数据表格(在这个例子中是dt2)的任何更改都会自动反映在 DataView 上。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接