我们可以将位置 SQL 转换为 C# LINQ 吗?

Can we Convert location SQL to C# LINQ?

这是一个 SQL 声明 returns 30 英里半径范围内的用户列表

SELECT
    id, (
      3959 * acos (
      cos ( radians(78.3232) )
      * cos( radians( lat ) )
      * cos( radians( lng ) - radians(65.3234) )
      + sin ( radians(78.3232) )
      * sin( radians( lat ) )
    )
) AS distance
FROM users
HAVING distance < 30
ORDER BY distance

我正在使用 C# .NET Web API2,是否可以将以上内容转换为 LINQ 语句以便我们可以API 获取此数据?

首先你需要为弧度定义这个方法

    public static double Radians(double angle)
    {
        return (Math.PI / 180) * angle;
    }

现在,您可以使用此查询

        var distances = users
            .Where(x => x.YourFilterOnPagination)
            .ToList() // your collection most be List 
            .Select(x => new
            {
                id = x.id,
                distance = (395 * Math.Acos(Math.Cos(Radians(78.3232)) *
                            Math.Cos(Radians(x.lat)) * Math.Cos(Radians(x.lat) - Radians(65.3234)) +
                            Math.Sin(Radians(78.3232)) *
                            Math.Sin(Radians(x.lat))))
            })
            .Where(d => d.distance < 30)
            .OrderBy(d => d.distance);

YourFilterOnPagination: If your data is big you can limits it in w