C# 如何使用LINQ获取范围内的记录列表
我试图在我的页面上集成Google地图,但是在集成之前,我需要从数据库中提取数据,我需要提取一个地方的lat和lon,然后我还要提取这些地方,它们也在提取的地方lat/lon附近 我有个问题需要澄清C# 如何使用LINQ获取范围内的记录列表,c#,linq,C#,Linq,我试图在我的页面上集成Google地图,但是在集成之前,我需要从数据库中提取数据,我需要提取一个地方的lat和lon,然后我还要提取这些地方,它们也在提取的地方lat/lon附近 我有个问题需要澄清 public static List<PlaceMap> GetPlace(this IEnumerable<Place> places, string hotelName, ref DataEntities ctx) { var place=
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;
}
这就是说,如果您有很多地方,例如数百万个,而您的数据库中没有空间索引,那么这样的查询可能会非常低效。显然,为了拥有空间索引,您需要使用空间类型来存储位置,而不是单独的纬度和经度列。在SQLServer中,您将使用SqlGeography列。可以使用实体框架作为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的是什么?你的方法签名表明你想返回一个列表,但是如果没有找到,你就给一个项目赋值为null,如果有几个酒店使用一个给定的名称给你的返回变量place,就会引发异常。另外-为什么这是IEnumerable上的一个扩展方法?方法中未以任何方式使用places变量。使用.Distance函数将导致覆盖圆形区域。由于OP希望在地图上显示这些,我假设需要一个矩形区域。DbGeography需要什么程序集引用?这就是我使用System.Data.Entity.Spatial查找System.Data.Entity的原因;好的,得到了所需的名称空间。我不明白我想写什么来代替你的RadiousInmeters?Kris有一点是关于圆形解决方案和矩形解决方案的区别他的解决方案这就是我目前数据库设计的工作原理。我没有数百万的名额。我最多只有210个@user3398887如果你只有210个位置,这就是你的答案。您不需要SqlGeography或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;
}