Select box-shape grid between two positions on tilemap

I want to be able to click and hold on a certain point and mark it as startPosition. Then, while the mouse is held down and moved, mark that second position as endPosition.

When the mouse is finally released, I want to get all the positions between those two points.

Here is my code so far:

for (float x = startPosition.x; x <= endPosition.x; x++)         {             for (float y = startPosition.y; y <= endPosition.y; y++)             {                 Vector3Int newPosition = Utilities.GridPosFromWorldPos(new Vector2(x, y));                 if (!selectedPositions.Contains(newPosition)) { selectedPositions.Add(newPosition); }             }         } 

This works only when dragging up and/or to the right. As soon as I try to go to left or bottom, the endPosition coordinates become smaller than the startPosition coordinates, which breaks the for loop.

How can I solve this?