André Marques
André Marques

Reputation: 178

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_;
    }
}

Upvotes: 0

Views: 328

Answers (2)

instantiator
instantiator

Reputation: 144

@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."

Upvotes: 3

obl
obl

Reputation: 1799

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]));
        }
    }

Upvotes: 4

Related Questions