之前Linq我从来没用过,实在是没有时间学习。我仅有的一点知识不足以做到这一点,我需要你的帮助。这是我需要转换为 Linq 的代码。(我正在使用EF6和上下文)
WITH messages AS (
SELECT s.siteId,s.originator,s.sentTime,s.mode,s.mainsFrequency,s.gensetFrequency,
s.dgBattery,s.runHours,s.fuel,s.messageID,s.messageText,
ROW_NUMBER() OVER(PARTITION BY s.originator
ORDER BY s.sentTime DESC) AS rk
FROM smsParseds s)
SELECT m.*
FROM messages m
WHERE m.rk = 1
order by m.sentTime DESC
在 Linq 中看到 Row_number over(按 xxx 划分)?用于进行分区。
其余的都是相当基本的 linq 语法。
我还没有测试过这个或尝试编译它,所以它可能需要一点修改。为了清楚起见,我将类似于问题的查询拆分开来,但这些查询可以很容易地合并为一行。
var messages = smsParseds
.OrderBy(o => o.sentTime).GroupBy(g => g.originator)
.Select(s => new {s, rk = s.Count()})
.SelectMany(sm => sm.s.Select(b => b)
.Zip(Enumerable.Range(1,sm.rk), (j,i) => new {j.siteId, j.originator, j.sentTime, j.mode, j.mainsFrequency, j.gensetFrequency, j.dgBattery, j.runHours, j.fuel, j.messageID, j.messageText, rk = i}));
var result = messages
.Where(w => w.rk = 1)
.OrderByDescending(o => o.sentTime)
这不是直接转换(实体框架不能使用行号),但结果应该是相同的
var query = from m in context.Messages
where (from x in context.Messages
where m.Originator == x.Originator
where x.SentTime > m.SentTime
select x).Any() == false
orderby m.SentTime desc
select new
{
m.siteId,
m.originator,
m.sentTime,
m.mode,
m.mainsFrequency,
m.gensetFrequency,
m.dgBattery,
m.runHours,
m.fuel,
m.messageID,
m.messageText,
};