views:

104

answers:

2

How can I write a query similar to this one in LINQ to SQL

SELECT Id, (Distance - someValue) as Res
FROM Table
WHERE Res < someOtherValue
ORDER BY Res
+1  A: 
MyTable
.Where(m => m.Res < 4)
.OrderBy(m => m.Res)
.Select(m => new {Id, Res = m.Distance - 4});

...where 4 is your someOtherValue

Andreas Grech
Why would Res be an available column it was only created as an alias in the select?
Jacob
You are just returning an Anonymous type, with only the fields you want...in this case, the Id and a custom-column called Red
Andreas Grech
+2  A: 

If you prefer keyword-style LINQ, it'd look something like this:

from x in theTable
where x.Distance < someOtherValue + someValue
orderby x.Distance
select new { x.Id, Res = x.Distance - someValue }
Jacob
you can use the let statement to avoid calculating x.Distance - someValue twice, ie to create the alias, before you evaluate the where condition
Nader Shirazie