0

I have a table where each row contains a team id, a user id and a boolean value indicating whether or not that user is a representative. Users can be representatives for more than one team and teams can have more than one representative. I'm trying to find out who is the most prolific representative and how many teams they are a representative for. Actually, I don't really care who it is, just how many teams they are a representative for.

I can do this easily in SQL with the below but I can't figure out how to write this in LINQ. I'd like to avoid a stored procedure if possible since they are very rarely used in this application and I'd like to maintain consistency.

SELECT MAX(a.RepCount) as TeamMaxRepCount
FROM
(SELECT DelegateUserID, COUNT(*) AS RepCount
FROM TeamDelegates
GROUP BY DelegateUserID) as a
1
  • maybe: int result = TeamDelegates.GroupBy(x => x.DelegateUserID).Max(g => g.Count()); Commented May 17, 2013 at 0:01

1 Answer 1

2

The other way round. E.g.:

var x = TeamDelegates.GroupBy(t => t.DelegateUserID)
                     .Select(t => new {
                                          DelegateUserID = t.Key,
                                          RepCount = t.Count()
                                      })
                     .Max(t => t.RepCount);

Which is the exact representation of your SQL query. This could even be simplyfied like sa_ddam213 mentioned in his comment.

Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't that be DelegateUserID = t.Key?
@recursive, of course it should! so, why didn't you write it that way?? ;-) Thank you!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.