سؤال

Okay, i have a list and where i have structs stored, and i need to go through them from the last to the first, to check if one of the variables in the struct is 1. the code look like this:

for(int i = (checkpoints.Count - 1); i == 0; i--)
{
    if(checkpoints[i].active == 1)
    {
        playerPositionX = checkpoints[i].xPosition;
        playerPositionY = checkpoints[i].yPosition;

        camPositionX = checkpoints[i].xPosition;

        break;
    }
}

this is the struct that i use:

private struct checkpoint
{
    public int xPosition;
    public int yPosition;
    public int active;
}

what i need to do is to check if the variable active is == 1 in the struct that i have stored in the list. i have around 3-8 structs stored in the list. I need to start the check from the last struct in the list and work my way to the first.

when i try to debug the program it looks like it's not going from the last, but it starts at i=0.

please leave a comment if you have a fix, or if you need more information.

هل كانت مفيدة؟

المحلول 2

Your mistake was that you said to go though the loop if i was equal to 0, when it wasn't. You want the loop to loop until i is greater or equal to zero.

for(int i = (checkpoints.Count - 1); i >= 0; i--)  // your mistake was here
{
    if(checkpoints[i].active == 1)
    {
        playerPositionX = checkpoints[i].xPosition;
        playerPositionY = checkpoints[i].yPosition;

        camPositionX = checkpoints[i].xPosition;

       break;
    }
}

نصائح أخرى

You can also use LastOrDefault() function. But, here can be one problem, because we are searching for Struct.

If nothing found?

LastOrDefault() will return default(checkpoint) if nothing found. The default value of a struct is the struct with all its values in turn default initialized. So, we must cast them to nullable using .Cast<checkpoint?>.

 var activeCheckPoint = checkpoints
      .Where(x => x.active == 1)
      .Cast<checkpoint?>()
      .LastOrDefault();

Or we must do the second check afterward that the returned object's active value is 1.

var activeCheckPoint = checkpoints.LastOrDefault(x => x.active == 1);
if(actactiveCheckPoint.active == 1)
{
    // Then it is Ok
}
else
{
     // Nothins was found
}

But, if you want to use for loop, then you must change i == 0 to i >= 0.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top