我有一个嵌套在foreach里面的foreach。我需要检查d是否小于其他所有的d。我怎样才能做到这一点?如果有办法查看先前设置的变量,那么我自己就能做到这一点。如果没有,你能设计一个解决方案吗?
这是我的代码:
foreach (DataRow newRow1 in dt.Rows)
{
string zipCode1 = newRow1[2].ToString();
double latitude2 = Convert.ToDouble(newRow1[3]);
double longitude2 = Convert.ToDouble(newRow1[4]);
foreach (DataRow newRow2 in dt2.Rows)
{
if (newRow2[2].ToString().Equals(zipCode1))
{
newRow1[5] = newRow2[1].ToString();
double latitude = Convert.ToDouble(newRow1[3]);
double longitude = Convert.ToDouble(newRow1[4]);
double d = Math.Sqrt(Math.Abs(latitude - latitude2) * Math.Abs(latitude - latitude2) + Math.Abs(longitude - longitude2) * Math.Abs(longitude - longitude2));
Console.WriteLine("Found match!");
}
}
}
答案 0 :(得分:2)
这相当于通过线性搜索找到min
的好旧算法:
foreach (DataRow newRow1 in dt.Rows)
{
string zipCode1 = newRow1[2].ToString();
double latitude2 = Convert.ToDouble(newRow1[3]);
double longitude2 = Convert.ToDouble(newRow1[4]);
// Start minD at the max value
double minD = double.MaxValue;
foreach (DataRow newRow2 in dt2.Rows)
{
if (newRow2[2].ToString().Equals(zipCode1))
{
newRow1[5] = newRow2[1].ToString();
double latitude = Convert.ToDouble(newRow1[3]);
double longitude = Convert.ToDouble(newRow1[4]);
double d = Math.Sqrt(Math.Abs(latitude - latitude2) * Math.Abs(latitude - latitude2) + Math.Abs(longitude - longitude2) * Math.Abs(longitude - longitude2));
minD = Math.Min(minD, d);
Console.WriteLine("Found match!");
}
}
Console.WriteLine("Min D: {0}", minD);
}