【发布时间】:2014-01-23 22:46:40
【问题描述】:
我有一个像这样的 DataTable -
EmpId,Country
1,Germany
2,Germany
3,UK
4,UK
5,UK
6,France
7,USA
8,USA
我想按国家/地区分组并将所有组提取到单独的数据表中。所以,我们 将有 4 个组/数据表。我该怎么做?
Stackoverflow 不允许我粘贴完整的工作代码。所以就到这里了,谢谢 @Myles B. Currie
测试代码 -
public void main()
{
DataSet ds = (DataSet) Dts.Variables["obj_Rs"].Value;
DataTable dt = ds.Tables[0];
List<DataTable> allCountryTables = new List<DataTable>();
DataView view = new DataView(dt);
DataTable distinctValues = view.ToTable(true, "Country");
//Create new DataTable for each of the distinct countries
//identified and add to allCountryTables list
foreach (DataRow row in distinctValues.Rows)
{
//Remove filters on view
view.RowFilter = String.Empty;
//get distinct country name
String country = row["Country"].ToString();
//filter view for that country
view.RowFilter = "Country = " + "'" + country + "'";
//export filtered view to new datatable
DataTable countryTable = view.ToTable();
//add new datatable to allCountryTables
allCountryTables.Add(countryTable);
}//for each
foreach(DataTable tbl in allCountryTables){
String table = getDataTable(tbl);
MessageBox.Show(table);
}//for
}//main
public static string getDataTable(DataTable dt){
string table = "";
foreach (DataRow dataRow in dt.Rows)
{
foreach (var item in dataRow.ItemArray)
{
table = table + item.ToString() + "|";
}//for
table = table + Environment.NewLine;
}//for
return table;
}//method
【问题讨论】:
-
按美国分组,您是指按国家/地区分组吗?
-
@TimSchmelter - 是的,我指的是国家。现在解决这个问题。
标签: c# .net datatable .net-3.5