views:

145

answers:

2

I have two tables an employee table and a project table and I am looking to bring back a count of the number of employees assigned to each project. In the employee table I have employeeIDs and projectIDs, and in the projects table I have projectID, name, department, notes, etc. I am looking to bring back the following information and display it in one single DataGrid in silverlight with the number of employees assigned to each project as a Count.

Name Department Notes Count

+2  A: 

There are many ways to do this, but the simplest is probably to do it like this:

var x =
    from proj in db.Projects
    select new
    {
     Name = proj.Name,
     Department = proj.Department,
     Notes = proj.Notes,
     Count = db.Employees.Where(emp => emp.ProjectID == proj.ProjectID).Count()
    };

Alternatively, if you created a foreign key between Projects and Employees on ProjectID (if not, you should strongly consider doing so), LINQ will kindly provide even cleaner syntax:

var x =
    from proj in db.Projects
    select new
    {
     Name = proj.Name,
     Department = proj.Department,
     Notes = proj.Notes,
     Count = proj.Employees.Count()
    };

It doesn't get any better than that!

Michael La Voie
+1...cleaner than mine...
CSharpAtl
In the event that you wanted to filter and count, you can still do it with just the Count method: Count = proj.Employees.Count(emp => emp.ProjectID > 10);
jrista
+1  A: 

I think you want something like this....

dbContext dbCon = new dbContext();
            var projects = from project in dbCon.Projects
                           join employee in dbCon.Employees on project.ProjectID equals employee.projectid
                           group employee by new { employee.projectid, project.Name, project.Department, project.Notes } into grouping
                           select new { 
                               //projectID = grouping.Key.projectid, 
                               projectName = grouping.Key.Name,
                               projectDepartment = grouping.Key.Department, 
                               projectNotes = grouping.Key.Notes, 
                               count = grouping.Count() 
                           };
CSharpAtl
Not as clean, but an excellent example of grouping...+1
Michael La Voie