Creating a Linq query

T

tony

Hello!

I have a DataTable with a lot of DataRows.
Each row has several DataColumn but here are the most relevant for my
question.
Groups and Units.
There are many DataRow having the same Groups.

I want to create a linq query that sum the Units for each Groups

//Tony
 
M

Mythran

tony said:
Hello!

I have a DataTable with a lot of DataRows.
Each row has several DataColumn but here are the most relevant for my
question.
Groups and Units.
There are many DataRow having the same Groups.

I want to create a linq query that sum the Units for each Groups

//Tony

Since you didn't specify whether the DataTable is typed, I'll use typeless
access:

Not sure if there is an easier way....here's one way that "seems" to work :)

DataTable tbl = new DataTable();
tbl.Columns.Add("Group", typeof(string));
tbl.Columns.Add("Units", typeof(int));

tbl.Rows.Add("Group #1", 12);
tbl.Rows.Add("Group #1", 26);
tbl.Rows.Add("Group #1", 32);
tbl.Rows.Add("Group #1", 41);
tbl.Rows.Add("Group #2", 34);
tbl.Rows.Add("Group #2", 36);
tbl.Rows.Add("Group #2", 32);

var groups =
from DataRow row in tbl.Rows
group row by row["Group"] into grouped
select new {
GroupName = (string) grouped.Key,
Units = (
(from item in grouped select item).Sum(p => (int) p["Units"])
)
};

foreach (var group in groups) {
Console.WriteLine(group.GroupName + " = " + group.Units.ToString());
}

HTH,
Mythran
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top