0
select TeamName, [Description], COUNT(u.UserId)
from Team t
left outer join [User] u on u.TeamId=t.TeamId
group by TeamName, Description, UserId

and here i have so far but cant able to do that.please help

var countUser = (from t in db.Teams
                 join u in db.Users on u.TeamId equals t.TeamId
                 group TeamName, Description, UserId by select  
                 new
                 {
                     u.UserId
                 }).Count();

2 Answers 2

1

This should do it:

Teams.Join(Users.DefaultIfEmpty().
        t => t.TeamId,
        u => u.TeamId,
        (t, u) => new { t.TeamName, t.Description, UserId = u == null ? null:(int?)u.UserId })
    .GroupBy(x => x)
    .Select(g => new { g.Key.TeamName, g.Key.Description, Count = g.Count() });
Sign up to request clarification or add additional context in comments.

3 Comments

i have to write this query for MVC Action method so how can i do that please help
@coolDude, I do not understand your question. What problems are you encountering in the action method?
i want to use this code in my controller take an example name of that action method is Index i want to write this code in that index action method . so when i apply your code into that it's showing me errors . i am very new to mvc that's why am facing these problems.please try to write as like var countUser = (from t in db.Teams join u in db.Users on u.TeamId equals t.TeamId group TeamName, Description, UserId by select new { u.UserId }).Count();
0

RePierre I'm going to steal part of your answer (+1) because I think I understand what OP is talking about, though the question text does not convey it.

You could do something like this:

// Model class for View
public class UsersPerTeamCount
{
    public string TeamName { get; set; }
    public string Description { get; set; }
    public int Count { get; set; }
}

// ...

public ActionResult PlayersPerTeam()
{
    var model = from t in db.Teams
                    join u in db.Users on t.TeamId equals u.TeamId into joinedRecords
                    select new UsersPerTeamCount()
                    {
                        Name = t.TeamName,
                        Description = t.Description,
                        PlayerCount = joinedRecords.Count()
                    };

    return View(model);
}

As far as in OPs comment "please try to write as like..." that's just a difference in syntax, it doesn't really matter which way you write it - either fluent vs query syntax (at least i think it's called query syntax)

1 Comment

first of all thanku for ur precious time. but as i told i am very new to linq and i dont know anything about it .that's why i post this question. dont mind i am not getting the syntax at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.