我有一个像这样的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
答案 0 :(得分:1)
这应该做的工作:
var countryGroups = dataTable.AsEnumerable()
.GroupBy(row => row.Field<string>("Country"));
请记住添加以下参考资料: System.Data.DataSetExtensions
答案 1 :(得分:1)
当然不是最简单的方法,但由于你说你有.Net版本问题,这是完成工作的漫长道路。 (以下代码未经测试)
DataTable table; //Your Datatable
List<DataTable> allCountryTables = new List<DataTable>();
//Get distinct countries from table
DataView view = new DataView(table);
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);
}
答案 2 :(得分:0)
您可以使用LINQ为每个国家/地区创建DataTable的子集:
Dim groups = From row In tblEmp
Let country = row.Field(Of String)("Country")
Group row By country Into Group
Select Group.CopyToDataTable()
Dim allCountryTables = groups.ToList()
哎呀,我确定有一个VB.NET标签....
var groups = from row in tblEmp.AsEnumerable()
let country = row.Field<string>("Country")
group row by country into Group
select Group.CopyToDataTable();
List<DataTable> allCountryTables = groups.ToList();