LINQ计算集合中的多个值

时间:2013-03-18 21:14:08

标签: c# linq

在SQL中,我想要完成的是

SELECT
            SUM(CASE WHEN Kendo=1 THEN 1 ELSE 0 END) as KendoCount,
            SUM(CASE WHEN Icenium=1 THEN 1 ELSE 0 END) as IceniumCount
FROM
            Contacts

我想在使用LINQ的C#程序中执行此操作。

联系人是一个列表,其中联系人有许多布尔人,如剑道和Icenium,我需要知道每个布尔人的真实数量。

4 个答案:

答案 0 :(得分:5)

至少在LINQ to SQL中,count函数的缺点是它需要为每个.count方法单独的SQL请求。我怀疑Jessie正在尝试对表执行单次扫描,而不是对每个谓词进行多次扫描。根据您创建的逻辑和列数,这可能不会执行。更接近原始请求,尝试使用带有三元if子句的sum(来自Northwind):

from e in Employees
group e by ""  into g
select new { 
    isUs = g.Sum (x =>  x.Country == "USA" ? 1 : 0),
    NotUs = g.Sum (x =>  x.Country != "USA" ? 0 : 1)
}

LINQ to SQL生成以下内容(YMMV与其他ORM):

 SELECT SUM(
    (CASE 
        WHEN [t1].[Country] = @p1 THEN @p2
        ELSE @p3
     END)) AS [isUs], SUM(
    (CASE 
        WHEN [t1].[Country] <> @p4 THEN @p5
        ELSE @p6
     END)) AS [NotUs]
FROM (
    SELECT @p0 AS [value], [t0].[Country]
    FROM [Employees] AS [t0]
    ) AS [t1]
GROUP BY [t1].[value]

答案 1 :(得分:3)

var KendoCount = db.Contacts.Where(x => x.Kendo).Count();
var IceniumCount = db.Contacts.Where(x => x.Icenium).Count();

答案 2 :(得分:3)

我会这样做两个单独的查询:

int kendoCount = db.Contacts.Count(c => c.Kendo);
int iceniumCount = db.Contacts.Count(c => c.Icenium);

鉴于这些查询将自动转换为优化的SQL,这可能与速度相似甚至可能比任何查询选项更快,并且更容易理解。


请注意,如果这是针对Entity Framework,则需要将其写为:

int kendoCount = db.Contacts.Where(c => c.Kendo).Count();
int iceniumCount = db.Contacts.Where(c => c.Icenium).Count();

答案 3 :(得分:1)

var result = Contacts
.GroupBy(c => new
{
    ID = "",
})
.Select(c => new
{
    KendoCount = c.Sum(k => k.Kendo ? 1 : 0),
    IceniumCount = c.Sum(k => k.Icenium ? 1: 0),
})
.ToArray()