如何使用LINQ在一个范围内获得记录列表

本文关键字:范围内 一个 列表 记录 LINQ 何使用 | 更新日期: 2023-09-27 17:50:19

我试图在我的页面上整合谷歌地图,但在我整合之前,我需要从数据库中提取数据,我需要提取一个地方的纬度和长度,然后我想提取那些地方也在附近提取的地方纬度/长度。

我有一个需要修改的查询

public static List<PlaceMap> GetPlace(this IEnumerable<Place> places, string hotelName, ref DataEntities ctx)
{             
   var place= ctx.places
       .Where(h=>h.HotelName==hotelName)
       .Select(s => new PlaceMap
       {
           PlaceName= s.PlaceName,
           Latitude = s.Latitude,
           Longitude = s.Longitude,
           NearByPlaces = ????
        }).SingleOrDefault();
    return place;
}

如何使用LINQ在一个范围内获得记录列表

查看实体框架的DBGeography:

public static List<PlaceMap> GetPlace(this IEnumerable<Place> places, string hotelName, ref DataEntities ctx)
{
    var place= ctx.places
        .Where(h=>h.HotelName==hotelName)
        .Select(s => new PlaceMap
        {
            PlaceName= s.PlaceName,
            Latitude = s.Latitude,
            Longitude = s.Longitude,
            NearByPlaces = ctx.places.Where
            (
                x=>
                DbGeography.FromText("POINT(" + s.Longitude + " " + s.Latitude + ")")  
                .Distance
                (
                    DbGeography.FromText("POINT(" + x.Longitude + " " + x.Latitude + ")")
                ) < YourRadiousInMeters
            )                  
        }).SingleOrDefault();
    return place;
}
NearByPlaces = (from p in ctx.places
                where p.Latitude > s.Latitude - latrange && 
                      p.Latitude < s.Latitude + latrange &&
                      p.Longitude > s.Longitude - longrange && 
                      p.Longitude < S.Longitude + longrange
                select /* whatever */).ToArray()

也就是说,如果您有很多位置(例如数百万)并且您的数据库上没有空间索引,那么这样的查询可能相当低效。显然,为了拥有空间索引,您需要使用空间类型来存储位置,而不是单独的Latitude和Longitude列。在SQL Server中,您将使用SqlGeography列。可以用实体框架作为DbGeography进行查询。

这应该回答你的实际问题,但它当然不会解决你的方法的其他问题,看看其他人对你的问题发表的评论