I'm really struggling with LINQ. I've written my query out in SQL (in effect it's a pivot), and trying to write an equivalent statement in LINQ. Any pointers forward would be much appreciated. See below for code:
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
Many Thanks.
I think this should do what you want - it's at least worth a try:
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),
};
This is how to do it:
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()
};
You can use the ?:
operator for your CASE
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With