title: How to use distinct with group by in Linq to SQL
body: <p>I'm trying to convert the following sql to Linq 2 SQL:</p>
  
  <pre><code>select groupId, count(distinct(userId)) from processroundissueinstance 
  group by groupId
  </code></pre>
  
  <p>Here is my code:</p>
  
  <pre><code>var q = from i in ProcessRoundIssueInstance
      group i by i.GroupID into g
      select new
      {
          Key = g.Key,
          Count = g.Select(x =&gt; x.UserID).Distinct().Count()
      };
  </code></pre>
  
  <p>When I run the code, I keep getting Invalid GroupID. 
  Any ideas? Seems the distinct is screwing things up..</p>
  
  <p>Here is the generated sql:</p>
  
  <pre><code>SELECT [t1].[GroupID] AS [Key], (
  SELECT COUNT(*)
  FROM (
      SELECT DISTINCT [t2].[UserID]
      FROM [ProcessRoundIssueInstance] AS [t2]
      WHERE (([t1].[GroupID] IS NULL) AND ([t2].[GroupID] IS NULL)) 
         OR (([t1].[GroupID] IS NOT NULL) 
              AND ([t2].[GroupID] IS NOT NULL) 
              AND ([t1].[GroupID] = [t2].[GroupID]))
      ) AS [t3]
  ) AS [Count]
  FROM (
      SELECT [t0].[GroupID]
      FROM [ProcessRoundIssueInstance] AS [t0]
      GROUP BY [t0].[GroupID]
      ) AS [t1]
  </code></pre>