Home > Net >  How to get the the index of an element in a triple nested array c#?
How to get the the index of an element in a triple nested array c#?

Time:10-12

So, I have this triple nested array deserialized from a JSON:

"Maps": [[[115.09049366110303, 116.30256509622684, 116.58246833041298]], [[25.0, 24.0, 58.0]]]

I'm already iterating over this triple nested array as it follows:

 public class Root
    {
        public List<List<List<double>>> Mapas { get; set; }
    }

    // Start is called before the first frame update
    void Start()
    {
        Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(textJson.text);  

    
        foreach (var item in myDeserializedClass.Maps)
        {
            foreach (var x in item)
            {
                foreach (var y in x)
                {
                   ...
                }
            }
        }    

    }

But since it's with foreach, how can I get the index of an specific element on that list, for example, the index of the element 25, so I can use this specific element somewhere else?

CodePudding user response:

well simplest way would be simply not use foreach

    for(var itemIndex = 0; itemIndex < myDeserializedClass.Mapas.Count; itemIndex  )
    {
        var item = myDeserializedClass.Mapas[itemIndex];

        for(var xIndex = 0; xIndex < item.Count; xIndex  )           
        {
            var x = item[xIndex];

            for(var yIndex = 0; yIndex < x.Count; yIndex  )
            {
               var y = x[yIndex];

               // Now you also have all indices "itemIndex", "xIndex" and "yIndex"
            }
        }
    }

then you store all three indices somewhere and can later also do

var y = myDeserializedClass.Mapas[itemIndex][xIndex][yIndex]
  • Related