繁体   English   中英

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

[英]How can I Get an original/parent object value in foreach 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()上?

您需要一个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肯定假定在Vector3上重写了ToString ,我不确定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM