![](/img/trans.png)
[英]How can I make a foreach loop work if 1 object meets the requirement?
[英]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.