如何在foreach循环中获取原始/父对象的值?

时间:2018-06-22 07:29:47

标签: c# for-loop

在代码初始化时,我定义了3个Vector3位置。

Vector3 A = new Vector3(377.999f, 326.656f, 103.566f);
Vector3 B = new Vector3(1137.728f, -981.551f, 46.416f);
Vector3 C = new Vector3(-1223.76f, -905.604f, 12.326f);

然后我为上面定义的每个Vector3提供了float对象。

   float Store_distance1 = World.GetDistance(my.Position, A); //Distance from my.pos to A
   float Store_distance2 = World.GetDistance(my.Position, B); //Distance from my.pos to B
   float Store_distance3 = World.GetDistance(my.Position, C); //Distance from my.pos to C

现在,当在一个方法中调用它时,我的定义如下。

private void SelectNearestStore()
    {
             List<float> NearestStore = new List <float>
             {
                 Store_distance1, Store_distance2, Store_distance3           
             };

              for (int i = 0; i < NearestStore.Count; i++)
                 {
                     if (NearestStore.Min() == NearestStore[i])
                      {
                        Console.write("Nearest Store is " + NearestStore[i].ToString() + " Meters Away");

                        Console.write("Location of the Store is " + //Vector3 property of A or B or C)
                      }

                 }

    }

比方说,Store_distance2是所有值中的最低值,

在这种情况下,我在第一个console.writeline()的for循环中获得了正确的浮点数。

如何获取B值以在第二个控制台writeline()中显示?

1 个答案:

答案 0 :(得分:1)

您需要一个Dictionary<Vector3, float>来保存矢量及其到您位置的距离:

var map = new Dictionary<Vector3, float>();
map[A] = World.GetDistance(my.Position, A); //Distance from my.pos to A
map[B] = World.GetDistance(my.Position, B); //Distance from my.pos to B
map[C] = World.GetDistance(my.Position, C); //Distance from my.pos to C

现在,您可以轻松打印每个矢量及其距离:

var min = map.Min(x => x.Value);
foreach(var kv in map)
{
    if (kv.Value == min)
    {
        Console.write("Nearest Store is " + min + " Meters Away");   
        Console.write("Location of the Store is " + kv.Key.ToString();
    }
}

最后一个Console.WriteLine肯定假定ToStringVector3覆盖,我不确定。