Linq到实体选择和统计?

时间:2011-07-12 00:04:52

标签: c# linq-to-entities

我有一张你可以在下面看到的表

表项目

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

我需要按类型分组,计算并计算销售的商品数量。 所以我可以得到你可以看到的结果

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

2 个答案:

答案 0 :(得分:5)

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) };

答案 1 :(得分:1)

 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)};