我从未在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
答案 0 :(得分:0)
见Row_number over (Partition by xxx) in Linq? 做分区。
其余的是相当基本的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)
答案 1 :(得分:-1)
这不是直接翻译(实体框架不能使用行号),但结果应该是相同的
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,
};