【问题标题】:How to get list of record within a range using LINQ如何使用LINQ获取范围内的记录列表
【发布时间】:2014-03-14 11:03:04
【问题描述】:

我正在尝试在我的页面上集成 Google 地图,但在集成之前,我需要从数据库中提取数据,我需要提取一个地方的纬度和经度,然后我想提取这些地方也在提取的地方纬度/经度附近。

我有一个查询需要修改

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;
}

【问题讨论】:

  • 希望您知道您的代码现在可以工作,无论您分配给NearByPlaces 什么?您的方法签名表明您想要返回一个List&lt;PlaceMap&gt;,但您正在为您的返回变量 (place) 分配一个项目(如果没有找到则为 null,如果有多个具有给定名称的酒店则抛出异常)。
  • 另外 - 为什么这是 IEnumerable&lt;Place&gt; 的扩展方法? places 变量未以任何方式在方法中使用。

标签: c# linq


【解决方案1】:

查看实体框架的 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;
}

【讨论】:

  • 使用 .Distance 函数会导致一个圆形区域被覆盖。由于 OP 想在地图上显示这些,我假设需要一个矩形区域。
  • DbGeography 需要哪些程序集参考?这就是我要找的
  • System.Data.Entity 使用 System.Data.Entity.Spatial;
  • Ok 得到了需要的命名空间。我不明白我想用什么来代替“YourRadiousInMeters”?
  • Kris 对圆(我的解决方案)和矩形(他的解决方案)的区别有一点看法
【解决方案2】:
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()

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

这应该回答您的实际问题,但它当然不会解决您的方法的其他问题,请参阅其他人针对您的问题发布的 cmets。

【讨论】:

  • 这对我来说适用于当前的数据库设计。我没有数以百万计的地方。我最多只有 210 个。
  • @user3398887 如果您只有 210 个位置,这就是您的答案。你不需要SqlGeography 也不需要DbGeography
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多