简体   繁体   English

C#中的数据集转换

[英]Dataset Conversion in C#

I have a dataset with a single datatable that goes as follows: 我有一个具有单个数据表的数据集,如下所示:

...
<description>"abcd"</description>
<date>"1/1/2001"</date>
... 
<description>"1234"</description>
<date>"1/1/2001"</date>
...
<description>"abcd"</description>
<date>"1/1/2001"</date>
...

I want to construct a new dataset, that contains the same values, rows and columns but only where the description is "abcd", per se. 我想构建一个新的数据集,它包含相同的值,行和列,但仅在描述本身为“ abcd”的地方。

ie, for the example values I gave, I'd like to get: 即,对于我给出的示例值,我想得到:

...
<description>"abcd"</description>
<date>"1/1/2001"</date>
... 
<description>"abcd"</description>
<date>"1/1/2001"</date>
...

I've seen the DataTable.Select() method, but I'm not sure if it's a good way or can work at all for what I'm trying to do. 我已经看过DataTable.Select()方法,但是我不确定这是个好方法还是完全可以为我要做的事情工作。

What's the best practice to do such a thing? 做这种事情的最佳实践是什么?

The Select method extracts an array of DataRow from the DataTable to which it is applied. Select方法从其应用到的DataTable中提取DataRow数组。

DataRow[] rows = ds.Tables[0].Select("description = 'abcd'");

Having the rows array declared you could check if there is something returned by the Select method and convert the array to a DataTable using the IEnumerable extension called CopyToDataTable 声明行数组后,您可以检查Select方法是否返回了某些内容,并使用名为CopyToDataTable的IEnumerable扩展将该数组转换为DataTable

DataTable foundData = null;
if(rows != null)
    foundData = rows.CopyToDataTable();

Notice that the DataSet is not involved in this process but it is just the container of your original table and the new table returned by CopyToDataTable is not included in the Tables collection of the DataSet. 请注意,该过程中不涉及数据集,但它只是原始表的容器,而由CopyToDataTable返回的新表不包含在数据集的Tables集合中。

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

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