I want to run the below SQL query in linq using a datatable
select
SUM(cast(Percentage as int))
,Subject
from tablename
where Student_ID = xxx
group by Subject_ID
How can I do it? Any help would be appreciated
I want to run the below SQL query in linq using a datatable
select
SUM(cast(Percentage as int))
,Subject
from tablename
where Student_ID = xxx
group by Subject_ID
How can I do it? Any help would be appreciated
Use Enumerable.GroupBy
, Sum
and an anonymous type to store the result:
var query = tablename.AsEnumerable()
.Where(row => row.Field<int>("Student_ID") == xxx)
.GroupBy(row => new { SubjectID = row.Field<int>("Subject_ID"), Subject = row.Field<string>("Subject") })
.Select(g => new
{
SumPercentage = g.Sum(r => r.Field<int>("Percentage")),
Subject = g.Key.Subject, SubjectID = g.Key.SubjectID
});
I don't know why you need to cast Percentage
to int
, but i'm pretty sure that you get it.