c# Linq select join on select group by
Posted
技术标签:
【中文标题】c# Linq select join on select group by【英文标题】: 【发布时间】:2011-09-15 11:18:51 【问题描述】:我有这个 MS-SQL 语句:
SELECT cv.id FROM ContactValue cv
INNER JOIN (
SELECT mainId, max(version) as v
FROM ContactValue
WHERE version <= $Version(int)
GROUP BY mainId
)
AS t ON t.mainId = cv.mainId AND t.v = cv.version
WHERE cv.contact_id = $ContactID(int)
AND cv.isActive = 1
ORDER BY sort'
并希望在 linq 中实现。 我确实将上述查询分为多个查询,但性能并不快。 是否存在任何 linq to linq 加入
我的 C# 代码:
var groupMax = from cv in db.ContactValue
where cv.contact_id == ContactID && cv.version <= Version
orderby cv.sort
group cv by cv.mainId into gcv
select new mainID = gcv.Key, version = gcv.Max(cv => cv.version) ;
foreach (var data in groupMax.ToList())
var Query = from cv in db.ContactValue
where cv.contact_id == ContactID && cv.mainId == data.mainID && cv.version == data.version && cv.isActive == true
select cv;
if (Query.Count() > 0)
ContactValue tmp = Query.First();
我希望所有联系人都有 1-2 个查询而不是 1 个查询,然后为每个联系人另一个查询...
请帮帮我!
【问题讨论】:
【参考方案1】:是的,Linq to SQL 确实实现了内部联接:
var groupMax =
from cv in db.ContactValue
where cv.contact_id == ContactID && cv.version <= Version
orderby cv.sort
group cv by cv.mainId into gcv
select new mainID = gcv.Key, version = gcv.Max(cv => cv.version) ;
var res =
from cv in db.ContactValue
join gm in groupMax on cv.version equals gm.version
where cv.contact_id == ContactID && cv.isActive
orderby cv.version ascending /*for example*/
select cv
【讨论】:
谢谢它的工作我只是在新的 cv.mainId, cv.version 等于新的 gm.mainId, gm.version 上更改了加入 gm,因为我需要使用多个条件加入。 .. 比我同时使用的要好得多:ExecuteStoreQuery受保护的无效 rptPriceRachiveBind()
using (MyEntities ctx = new MyEntities())
var catRef = Convert.ToInt32(Request.QueryString["CategoryRef"]);
var prodCounts = (
from A in ctx.Products
join B in ctx.ProductPrices
on A.ProductId equals B.ProductRef
where A.CategoryRef == catRef
group A by new A.Name,B.ProductRef into catGp
select
new
catGp.Key.ProductRef,
catGp.Key.Name,
proIdCount = catGp.Count()
).ToList();
Repeater1.DataSource = prodCounts;
Repeater1.DataBind();
【讨论】:
以上是关于c# Linq select join on select group by的主要内容,如果未能解决你的问题,请参考以下文章
C# LINQ 详解 From Where Select Group Into OrderBy Let Join