Trade foreach for for

Asked

Viewed 339 times

4

I need to change the following foreach() by a for(). The problem is that instead of arrays the loop runs through a dictionary. This is the code I want to transform 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 + ",");
}

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

Link to the implementations of class.

2 answers

4

Cycles should not be used for with a dictionary, because the dictionary, 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 Indian is a malpractice.

If you need access to Keys, use a cycle foreach on the pairs, instead of on 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 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 will try to offer you a solution to the specific problem, which may be to use a:

4


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;
  //...
}
  • 3

    I don’t think this is going to be a problem in practice, but I understand that .ElementAt(index) generally takes time O(index)? I do not know what the pmargreff wants to do, but the possibility of creating a List<T> or T[] temporary and use this temporary object may best suit what he wants.

  • Worked, grateful.

  • I thought the list idea was cool.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.