Andrew Venture
Andrew Venture

Reputation: 327

Linq to entity select and count?

I have a table like you can see below

Table items

ID          Type               Sold (bit)
--------------------------------------------
1           Book                 1
2           Phone                0
3           TV                   1
4           TV                   1
5           TV                   1
6           TV                   0
7           Phone                1
8           Phone                0

I need to group by type, count it and count how many items are sold. So I can get the result like you can see below

Phone 3; Sold 1
TV    4; Sold 3
Book  1; Sold 1

Upvotes: 0

Views: 2640

Answers (2)

Jeff Mercado
Jeff Mercado

Reputation: 134811

var query = from row in table
            group row.Sold by row.Type into g
            select new { Type = g.Key, Count = g.Count(), Sold = g.Count(s => s) };

Upvotes: 5

Thomas Li
Thomas Li

Reputation: 3338

 var result = 
 from p in products 
 group p by p.Type into g 
 select new {TypeDesc = g.Key, NumberOfIDs = g.Count(p => p.ID), UnitsSold = g.Sum(p => p.Sold)}; 

Upvotes: 1

Related Questions