如何将SELECT MAX语句从SQL转换为LINQ到SQL?

时间:2018-07-19 15:49:57

标签: c# linq linq-to-sql

我正在尝试将此SQL语句转换为LINQ to SQL。

SELECT [PurpCode],
MAX(([PurpCode] + ' - ' + [Purpose])) AS [PurposeName]
FROM [dbo].[CCM]
WHERE [PurpCode] IS NOT NULL AND [PurpCode] <> ''
GROUP BY [PurpCode]
ORDER BY [PurpCode]

我已经走了这么远:

    db.CCM
      .Where(ccm.PurpCode != null && ccm.PurpCode != "")
      .Select(ccm => new { ccm.PurpCode, PurposeName = ccm.PurpCode + " - " + ccm.Purpose })
      .Max(ccm => ccm.PurposeName)
      .GroupBy(ccm => ccm.) //Properties on ccm disappear after .Max
      .OrderBy(ccm => ccm.) 

Max在LINQ中的工作方式似乎与在SQL中不同。我在SQL Server中将其用作仅在PurposeName列上运行的准DISTINCT。在.Max之后做任何尝试的尝试都不起作用,因为ccm上的所有属性都丢失了。

1 个答案:

答案 0 :(得分:2)

使用OrderBy对每个组的元素进行排序,然后使用FirstOrDefault获取第一个。

db.CCM
    .Where(ccm.PurpCode != null && ccm.PurpCode != "")
    .Select(ccm => new { ccm.PurpCode, PurposeName = ccm.PurpCode + " - " + ccm.Purpose })
    .GroupBy(ccm => ccm.PurpCode)
    .Select(grp=> new {  
          grp.Key, 
          PurposeName = grp.OrderBy(x=> 
              x.PurposeName).FirstOrDefault() });