我有这个代码工作100%,计算两个对象之间的距离
public double CalculateDistance(string storelocator_id, BO_MAGASIN magasin)
{
double response = 0;
var getMagasin = _context.Magasin.FirstOrDefault(x => x.storelocator_id.Equals(storelocator_id));
double distance = 0;
var myMagasin = _context.Magasin.FirstOrDefault(x => x.storelocator_id.Equals("1"));
string sql;
var magasins = _context.Magasin.ToList();
if (storelocator_id != null)
{
string latitude = getMagasin.latitude;
string longitude = getMagasin.longitude;
string magasin_latitude = magasin.latitude;
string magasin_longitude = magasin.longitude;
sql = "set @pt1= point(" + latitude + "," + longitude + "); set @pt2= point(" + magasin_latitude + "," + magasin_longitude + "); SELECT ST_Distance_Sphere(@pt1, @pt2)/1000";
try
{
MySqlDataReader reader = null;
string selectCmd = sql;
string dbConn = configuration.GetSection("ConnectionStrings").GetSection("Default").Value;
var conn = new MySqlConnection(dbConn);
conn.Open();
MySqlCommand command = new MySqlCommand(selectCmd, conn);
reader = command.ExecuteReader();
if (reader.Read())
{
response = double.Parse(reader[0].ToString());
if (distance > response)
{
distance = response;
}
}
conn.Close();
}
catch (Exception ex)
{
}
}
return distance;
}
我有其他代码返回BO_MAGASIN的列表,但现在我想按距离排序此列表,任何人都知道我如何才能做到这一点?
1条答案
按热度按时间0md85ypi1#
您可以使用以下函数在C#中计算这些点之间的距离(使用spherical triangles计算距离)
要按距离对列表排序,请使用Linq
.OrderBy()
。顺便说一句:如果你想让结果以公里为单位,只需删除
factor
。