从lambda(方法)语法转换为查询语法(LINQ)

时间:2014-03-28 22:34:44

标签: c# linq lambda linq-method-syntax

如何翻译

var vehiclequery = db.position
    .GroupBy(c => c.device_id)
    .Select(g => g.OrderByDescending(c => c.sendtime).FirstOrDefault())
    .Select(c => new myPosition()                                                          
    {
        battery_percentage = c.battery_percentage,
        device_id = c.device_id,
        latitude = c.latitude,
        longitude = c.longitude,
        speed = c.speed,
        sendtime = c.sendtime
    });

查询语法?现在我有一些愚蠢的东西,我不知道如何使它工作。这是这样的吗?

var vehiclequery = from dPosition in db.position
                   group dPosition by dPosition.device_id into xx
                   select new
                   {
                       device_id = xx.device_id
                   };

我知道有很多东西不见了但是我已经陷入了困境。我尝试了在堆栈上推荐的工具 - http://www.linqpad.net/,但这只是从查询语法转换为方法语法。

感谢您提供帮助或领导如何完成这项工作。一些有用的手册页也会非常感激,现在我只使用http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

1 个答案:

答案 0 :(得分:4)

这不是一对一的转录,因为let的工作方式(您仍然可以在xx之后访问let),但会产生相同的结果:

var vehiclequery = from dPosition in db.position
                   group dPosition by dPosition.device_id into xx
                   let c = xx.OrderByDescending(x => x.sendtime).FirstOrDefault()
                   select new
                   {
                       battery_percentage = c.battery_percentage,
                       device_id = c.device_id,
                       latitude = c.latitude,
                       longitude = c.longitude,
                       speed = c.speed,
                       sendtime = c.sendtime
                   };

或将子查询作为语法查询:

var vehiclequery = from dPosition in db.position
                   group dPosition by dPosition.device_id into xx
                   let c = (from x in xx
                            orderby x.sendtime desc
                            select x).FirstOrDefault()
                   select new
                   {
                       battery_percentage = c.battery_percentage,
                       device_id = c.device_id,
                       latitude = c.latitude,
                       longitude = c.longitude,
                       speed = c.speed,
                       sendtime = c.sendtime
                   };