I have a query like this:
SELECT [degree_id], [institution_id]
FROM [dbo].[instlist]
where [degree_id]=1
group by institution_id, degree_id
I need to count total rows, so I then use a for loop to get count and then return it. How to convert the query above in Linq? Thanks.
[HttpGet]
public int GetDegreeCountByInstitution(int degreeid)
{
var qry = db.instlist
.GroupBy(g => new { g.degree_id, g.institution_id })
.Select(n => new { degree_id=n.degree_id, institution_id=n.institution_id });
var cnt=0;
for( int i=0; i<qry.ToList().Count; i++)
{
cnt = cnt + 1;
}
return cnt;
}
There is an error on the select statement.
答案 0 :(得分:0)
类似的东西:
var q = (from id in instlist
where id.degree_id == 1
select id.degree_id, id.institution_id).Distinct().Count()
答案 1 :(得分:0)
您可以对count
;
group by
var result = db.instlist.Where(x => x.degree_id == 1)
.GroupBy(x => new { x.degree_id, x.institution_id })
.Select(g => new
{
degree_id = g.Key.degree_id,
institution_id = g.Key.institution_id,
count = g.Count()//Apply count for grouped records
}).ToList();