tags:

views:

121

answers:

1

i have a table

Id Number
1   9
2   10
3   12
4   19
5   20

select Id where Number is closest to 18 it should return row 4 which is 19

how do i write this in linq and tsql? thanks

+6  A: 
(from q in table
 orderby Math.Abs(18 - q.Number)
 select q).FirstOrDefault()

and

SELECT TOP 1
    *
FROM
    table
ORDER BY
    ABS(10 - Number)

and for a datetime

var nearTo = new DateTime(1999, 12, 31);
(from q in table
 orderby Math.Abs((nearTo - q.Date).TotalSeconds)
 select q).FirstOrDefault()
John Gietzen
Oops - I think you mean Math.Abs(18 - q.Number). +1 though.
Matt Hamilton
what if it's a datetime type?
scrippie
It will work, except you have to get the TotalSeconds or similar from the timespan returned.
John Gietzen
thank you so much!
scrippie
No problem, glad I could help.
John Gietzen
Oh, keep in mind that "TotalSeconds" may not be the best actual measure for two reasons: It may not be granular enough, and, you may get arithmetic overflows.
John Gietzen