2011-08-08 45 views
2

我對Linq to Entity很陌生,遇到一些麻煩。按Linq排序進行數學計算

這裏是我的搜索庫:

public static List<Centre> Search(Search search) 
{ 
    using (var context = new MeetingRoomsContext()) 
    { 
     var query = context.Centres 
       .Include("Geo") 
       .OrderBy(NEED HELP WITH THIS PART) 

     return query.ToList(); 
    } 
} 

我得到包含座標這樣的搜索對象:

Search.LongLat = "(-6.265275, 53.334442)" 

我要打破了,做對了合作的一些數學在DB中的下屬,以便按照距離搜索點最近的順序排序結果。

在數學方面這將是畢達哥拉斯:

squareRootOf((difference in latitude * difference in latitude) + 
      (difference in longitude * difference in longitude)) 

真的沒有線索如何做到這一點。任何幫助極大地讚賞

+2

在Sql Server 2008中有一個空間索引功能,它可以幫助處理這些場景,但我認爲它不被EF支持。 –

回答

3

根本不需要平方根;排序由所述距離的平方是與由距離排序:

.OrderBy(x => (x.Latitude - target.Latitude)*(x.Latitude - target.Latitude) 
       + (x.Longitude - target.Longitude)*(x.Longitude - target.Longitude)) 

這招通常在碰撞檢測(如視頻遊戲)所使用,以避免必須計算許多平方根。

0

如何實現自己的IComparer計算畢達哥拉斯平方根?然後OrderBy會自動比較。
查看this post爲例。