使用LINQ编写案例语句(使用GROUP BY)

时间:2012-02-13 16:59:12

标签: c# .net sql linq entity-framework

我真的在努力学习LINQ。我已经在SQL中编写了我的查询(实际上它是一个支点),并尝试在LINQ中编写一个等效语句。任何指针都将非常感激。请参阅下面的代码:

SELECT b.URL,
SUM(CASE WHEN (a.ExtFlag = 0) THEN 1 ELSE 0 END) AS IntLinks,   
SUM(CASE WHEN (a.ResponseCode >= 400 AND a.ExtFlag = 0) THEN 1 ELSE 0 END) AS IntBroken,
SUM(CASE WHEN (a.ExtFlag = 1) THEN 1 ELSE 0 END) AS ExtLinks,   
SUM(CASE WHEN (a.ResponseCode >= 400 AND a.ExtFlag = 1) THEN 1 ELSE 0 END) AS ExtBroken
FROM Link a
INNER JOIN Host b
ON a.HostID = b.ID
GROUP BY b.URL
ORDER BY b.URL

非常感谢。

2 个答案:

答案 0 :(得分:9)

我认为这应该做你想要的 - 至少值得一试:

var query = from link in db.Links
            join host in db.Hosts on link.HostID equals host.ID
            group link by host.Url into links
            select new
            {
                Url = links.Url,
                IntLinks  = links.Count(link => link.ExtFlag == 0),
                IntBroken = links.Count(link => link.ExtFlag == 0 &&
                                                link.ResponseCode >= 400),
                ExtLinks =  links.Count(link => link.ExtFlag == 1),
                ExtBroken = links.Count(link => link.ExtFlag == 1 &&
                                                link.ResponseCode >= 400),
            };

答案 1 :(得分:2)

这是怎么做的:

from a in db.Links
group a by a.Host.Url into g
select new
{
    Url = g.Key,
    IntLinks = (
        from x in g
        select x.ExtFlag == 0 ? 1 : 0)
        .Sum()
};

您可以?:使用CASE运算符。