jackncoke
jackncoke

Reputation: 2020

Is this the correct way to use LINQ Group By?

I have two tables. Cars and Dealers. Each car has a dealerID associated with it. Each dealer has a state attribute. I need to write a query that will tell me how many cars there are per state in the database. I have not had to use group by yet but I think this is what it is used for. This is as far as i got before i realized i needed help.

        var query = (from c in _db.Cars
                     join d in _db.Dealers on c.DealerID equals d.DealerID
                     where c.Active == true
                     group c by d.State);

Goal is to have a listview list each state with the total cars per state as the end results.

Upvotes: 1

Views: 52

Answers (1)

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18411

Let me help by writing it in extensions method:

var query = 
_db.Cars
.Join
(
    _db.Dealers,
    c=>c.DealerID,
    d=>d.DealerID,
    (car,dealer)=>new {car,dealer}
)
.Where
(
    x=>x.car.Active//no reason to check with == true if this is boolean
)
.GroupBy
(
    x=>x.dealer.State
)
.Select
(
    x=>new 
    {
        State = x.Key,
        Cars = x.Count()
    }
);

Upvotes: 3

Related Questions