20
\$\begingroup\$

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 or shorter?

Malachi
29k11 gold badges86 silver badges188 bronze badges
asked May 25, 2011 at 5:01
\$\endgroup\$
1
  • \$\begingroup\$ R u using Entity Framework to Linq to SQL? \$\endgroup\$ Commented May 25, 2011 at 10:16

1 Answer 1

8
\$\begingroup\$

Your j and i variables are pretty plain and won't make this code fun to maintain (especially if it were a big block of code)

You should use more descriptive variables.

you should create a collection that groups the Jobs by their Industry and then select from that collection the industry name and the count of jobs in the collection with that name.

from job in dbConnection.jobs
join industry in dbConnection.industries on job.industryId equals industry.id
group new {industry, job} by industry.Name
into jobsByIndustry
select new {
 industryName = jobsByIndustry.Key.Name,
 jobscount = jobsByIndustry.Count()
}
answered Apr 17, 2014 at 14:05
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.