简体   繁体   中英

List Returning 0 after Adding values through a for loop - c#

After this method my List count return 0 while it shouldn't. All the debugs are correct neither of them is null or something. I am using Unity. Does anyone know where is the problem?

List<Coordinates> FillCoordinates()
{
    List<Coordinates> coordinatesList = new List<Coordinates>();
    Debug.Log(minLenght);
    Debug.Log(maxLenght);
    Debug.Log(heights.Count);
    for (int i = minLenght; i > maxLenght; i++)
    {
        for (int j = 0; j < heights.Count; j++)
        {
            coordinatesList.Add(new Coordinates(i, heights[j]));
        }
    }

    return coordinatesList;
}

Coordinates class:

public class Coordinates
{
    public int lenght;
    public float height;

    public Coordinates(int lenght_, float height_)
    {
        lenght = lenght_;
        height = height_;
    }
}

I'm guessing this never executes, change i < maxLenght

    for (int i = minLenght; i > maxLenght; i++)
    {
        for (int j = 0; j < heights.Count; j++)
        {
            coordinatesList.Add(new Coordinates(i, heights[j]));
        }
    }

@obl is right, this will not execute:

for (int i = minLenght; i > maxLenght; i++)

The for-loop statement reads: "Start with i at minLength , and while i is greater than maxLength , run the loop and then increment i ."

As i isn't greater than maxLength, the loop will never run.

Change it to this:

for (int i = minLenght; i < maxLenght; i++)

"Start with i at minLength , and while i is less than maxLength , run the loop and then increment i ."

It will now run from minLength all the way up to maxLength-1 .

You are right that this won't run the loop one final time when i is equal to maxLength . To fix that (if it's really what you want), simply adjust it like this:

for (int i = minLenght; i <= maxLenght; i++)

"Start with i at minLength , and while i is less than or equal to maxLength , run the loop and then increment i ."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM