Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have two tables, one for jobs, and one for the names of industries (e.g. automotive, IT, etc).

In SQL I would just do:

    SELECT industryName, count(*)
    FROM jobs
    JOIN industry
    ON jobs.industryId = industry.id
    GROUP BY industryName

In LINQ I have the following, but it's three separate statements and I'm pretty sure this would be doable in one.

    var allIndustries =
        from j in dbConnection.jobs
        join i in dbConnection.industries on j.industryId equals i.id
        select i.industryName;
    var industriesWithCount =
        from i in allIndustries
        group i by i into iGrouped
        select new { Industry = iGrouped.Key, Count = iGrouped.Count() };
    var industries = new Dictionary<string, int>();
    foreach (var ic in industriesWithCount)
    {
        industries.Add(ic.Industry, ic.Count);
    }

Is there a way to make this simpler / shorter?

share|improve this question
R u using Entity Framework to Linq to SQL? – AMgdy May 25 '11 at 10:16

1 Answer

up vote 10 down vote accepted
from j in dbConnection.jobs
join i in dbConnection.industries on j.industryId equals i.id
group new {i, j} by new {
  i.Name
} into g

select new {
  industryName = g.Key.Name,
  jobscount = g.Count()
}
share|improve this answer
1  
missing "on" after join.. – Rajesh Rolen- DotNet Developer May 25 '11 at 10:48
Just updated it – AMgdy May 25 '11 at 10:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.