将sql转换为LINQ查询,以便在c#中选择多个最大列

时间:2017-11-28 09:39:32

标签: c# sql-server linq

SELECT MAX(sectionid) AS SectionId,MAX(displayorder) AS DisplayOrder,propertyid AS PropertyId,1 AS IsSpecSection FROM (
    SELECT mp.SectionId ,mp.DisplayOrder ,mp.PropertyId  FROM 
   ModelProperties mp 
    INNER JOIN PropertySections PS ON mp.SectionId = 
     ps.SectionId 
WHERE ps.IsSpecSection = 1  )s 
GROUP BY propertyid

我想将上述查询转换为LINQ,能够选择单个最大列而不是多个。

2 个答案:

答案 0 :(得分:0)

我没有测试您需要修改代码的代码

using (var dbContext = new YourEntityName())
            {
                var result = (from mp in dbContext.ModelProperties
                              join ps in dbContext.PropertySections on mp.SectionId equals ps.SectionId
                              where ps.IsSpecSection = 1
                              group a by new { propertyid } into g
                              select sectionid , MAX(displayorder)AS DisplayOrder,propertyid AS PropertyId, 1 AS IsSpecSection).ToList(); 

}

Max value in Linq select Within Innerjoin

答案 1 :(得分:0)

您可以使用此代码

var list=(from mp in ModelProperties
          join ps in PropertySections on mp.SectionId equals ps.SectionId 
          where ps.IsSpecSection == 1
          group  new { mp, ps } by new { mp.PropertyId } into mgrp
          from grp in mgrp.DefaultIfEmpty()  
          select new
          { 
             grp.mp.SectionId, 
             grp.mp.PropertyId,
             grp.mp.DisplayOrder,
             grp.ps.IsSpecSection
          }).OrderByDescending(x=>x.SectionId).First(); 

此查询可帮助您检索ModelProperties中匹配SectionId的{​​{1}}行,PropertySections的值为1.匹配的行然后按{{1}分组}。 IsSpecSectionPropertyId的降序对检索到的结果进行排序。 OrderByDescending检索每个SectionId最多First()的行,因为行按SectionId的降序排序。