我正在尝试将此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
上的所有属性都丢失了。
答案 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() });