开发者

linq sql where closest to number

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开发者_StackOverflow中文版 which is 19

how do i write this in linq and tsql? thanks


(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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜