Search code examples
c#linqlambdalinq-method-syntax

Translate from lambda (method) syntax to query syntax (LINQ)


how it's possible to translate

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
    });

to query syntax? Now I have just something stupid and I have no idea how to make it work. It's something like this?

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

I know there are lot of things missing but I'm stuck at this point. I tried tool that was reccomended here on stack - http://www.linqpad.net/, but this only translate from query syntax to method syntax.

Thanks for any help or leads how to make this work. Some useful manual pages would be also very appreciated, now I'm using just http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b


Solution

  • It's not a 1-to-1 transcription, because of how let works (you still have access to xx after let), but will produce the same results:

    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
                       };
    

    or with sub query as a syntax query:

    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
                       };