I have a DataTable that looks like the below:
Category | Amount
Food | 10
Drink | 20
Clothes | 50
Drink | 30
Food | 40
Clothes | 5
I want to group it by the Category column and convert each similar grouping into a DataTable and place it inside a List . So I need to have 3 DataTables like the below:
DataTable 1
Category | Amount
Food | 10
Food | 40
DataTable 2
Category | Amount
Drink | 20
Drink | 30
DataTable 3
Category | Amount
Clothes | 50
Clothes | 5
Any advice on how to achieve the above? I can only find questions that want to have an output of 1 DataTable.
You can use Linq to objects (and Linq to Dataset) this way
List<DataTable> tablesByCategory =
table.AsEnumerable().
GroupBy(r => r.Field<double>("Category")).
Select(g =>
{
DataTable dt = table.Clone();
foreach (DataRow r in g)
{
dt.ImportRow(r);
}
return dt;
}).ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.