开发者

linq sql where closest to number

开发者 https://www.devze.com 2022-12-11 13:09 出处:网络
i have a table Id Number 19 210 312 419 520 select Id where Number is closest to 18 it should return row 4开发者_StackOverflow中文版 which is 19

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

精彩评论

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