c#Linq在select group by上选择join

本文关键字:选择 join by group select c#Linq | 更新日期: 2023-09-27 17:59:16

我有这个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

我的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个查询,而不是一个查询,然后为每个联系人另一个查询。。。

请帮帮我!

c#Linq在select group by上选择join

是的,Linq到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

protected void 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();
        }