Reputation: 2467
I have a DataTable in C# with two columns
State Region
A 1
A 2
B 3
B 4
What I want to achieve is
State Region
A 1,2
B 3,4
Is this possible in C# with a single LINQ query?
I am not good in LINQ and also don't want to loop through table to achieve that.
Upvotes: 2
Views: 3461
Reputation: 75316
var result = dataTable.AsEnumerable()
.GroupBy(row => row.Field<string>("State"))
.Select(g =>
{
var row = dataTable.NewRow();
row.ItemArray = new object[]
{
g.Key,
string.Join(",",
g.Select(r => r.Field<string>("Region")))
};
return row;
}).CopyToDataTable();
Upvotes: 1
Reputation: 2325
Use GroupBy to achieve this as follow....
var groupedData = from b in dataTable.AsEnumerable()
group b by b.Field<string>("State") into g
select new
{
State = g.Key,
Regions = g,
};
Then you can iterate through each group to get Data...
foreach (var g in groupedData)
{
foreach (var w in g.Regions)
{
Console.WriteLine(w);
}
}
Upvotes: 0