views:

22

answers:

1
  • An employee can have multiple vehicles..
  • And a company can have multiple employees..

My mission is to get the Companies that therefore have the most vehicles..

I have the LINQ query working perfectly (phew)! It returns (via select new {})..

  • CompanyID
  • EmployeeVehicleCount

Fantastic! BUT.. I want to be able to pull out "Company" objects rather than just the int CompanyID, so that I could essentially access them like this while iterating through the results:

ResultRow.Company.CompanyName

And

ResultRow.EmployeeVehicleCount

Otherwise, I am going to have to first set up a loop and then instantiate each and every Company as I go through the loop which doesn't seem very efficient.

What's the cleanest way to achieve what I'm after? (Thx in advance).

+1  A: 

if you have the companyid and vehiclecount, you can transform that via a new Select ala

var list = <your existing linq query>.Select(o => new { Company = <SomeDataMethod>(o.CompanyID), EmployeeVehicleCount = o.EmployeeVehicleCount });

now you can say

foreach (var result in list) 
{
   var s = result.Company.CompanyName +" has "+ result.EmployeeVehicleCount +" cars";
}
BurningIce
Thanks for the response. The first part is gold and works beautifully - many thanks!!! Unfortunately the second snippet isn't working for me. I get: "'object' does not contain a definition for 'Company' and no extension method 'Company' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?" The compiler has no idea that there is a "Company" object inside it. Any thoughts?
Aaron
Ok I can get it working within the context of the same method when everything is just a var. But as soon as I return the list as the result of a method, it no longer works outside that method because if I pass it as type object, it says objects can't be enumerated by foreach. But if I pass it as an IQueryable/IEnumerable, then it says "it doesn't contain a definition for 'Company'..." as per above etc..
Aaron
I really don't want to make a custom class/struct for every single query that does a group by count.
Aaron
I found a pretty pain free solution to the second problem by just using a super lightweight struct, which you make public in your data repository class so that everything can see it. Works perfectly and now the results from my query can be strongly typed so that they can be passed through the controller and into the View for example. E.g. public struct QueryResultCompanyWithCount{ public Company TheCompany { get; set; } public int Count { get; set; } }And so I can make my method signature: public IQueryable<QueryResultCompanyWithCount> GetCompaniesWithMostVehicles() and manipulate that!
Aaron