Change foreach by for

4

I need to change the following foreach() to for() . The problem is that instead of arrays the loop runs through a dictionary. This is the code I want to transform a for() :

foreach (var joint in body.Joints.Values)  //transformar em um for para usar valoren anteriores
{
  eixoX = joint.Position.X.ToString();
  eixoX = eixoX.Replace(",", ".");
  line.Append(eixoX + ",");

  eixoY = joint.Position.Y.ToString();
  eixoY = eixoY.Replace(",", ".");
  line.Append(eixoY + ",");
}

By not mastering C # I was confused to do this.

Link to the implementations of class .

    
asked by anonymous 16.06.2015 / 17:20

2 answers

4

Do you want something like this?

for (int index = 0; index < body.Joints.Count; index++) {
  var item = body.Joints.ElementAt(index);
  var jointType = item.Key;
  var joint = item.Value;
  //...
}
    
16.06.2015 / 17:35
4

for cycles should not be used with a dictionary, because the dictionary is by nature is not ordered .

  

The order in which the items are returned is undefined.

So trying to access key-value pairs of the dictionary by index is bad practice .

If you need access to the keys, use a foreach loop over the pairs instead of the Values .

foreach (var pair in body.Joints)
{
    var x = pair.Key;
    var y = pair.Value;

}

In a comment you say you want to "use previous values". As I have already explained, there is no concept of value previous in a dictionary because there is no definite order. If you explain better what you're trying to do, I'll try to give you a solution to the specific problem, which might be to use one:

17.06.2015 / 10:00