Skip to content
Advertisement

Find rows that have the same value on a column in asp.net

I have an issue I want to translate this SQL query int asp.net. there is a relationship between student table and teacher table many to many and I want to display students that have more than one teacher

select COUNT(StudentId), StudentId  from StudentTeachers 
group by StudentId
 having COUNT(StudentId)> 1


and that what I trying to do in asp.net

 var data = db.StudentTeachers.
                Join(db.Students, a => a.StudentId, b => b.ID, (a, b) =>a).GroupBy(x=> x.StudentId);


Advertisement

Answer

You can try out both ways.

Using Lambda Expressions

            db.StudentTeachers.GroupBy(s => s.StudentId)
                  .Where(grp => grp.Count() > 1)
                  .Select(grp => new
                  {
                      StudentCount = grp.Count(),
                      StudentId = grp.Key
                  }).ToList();

Using SQL like query expressions

from s in db.StudentTeachers
group s by s.StudentId into grp
where grp.Count() > 1
select new { StudentId = grp.Key, StudentCount = grp.Count() }).ToList();

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement