# Sorting a list by three parameters (C#)

I have this list called “Block”. Each item has four parts being a string called “block”, and three floats for each coordinate:

``````public class Block : IComparable<Block>
{
public string block;
public float xLocation;
public float yLocation;
public float zLocation;

public Block (string newBlock, float newXLocation, float newYLocation, float newZLocation)
{
block = newBlock;
xLocation = newXLocation;
yLocation = newYLocation;
zLocation = newZLocation;
}
}
``````

I want to order the blocks first by lowest x value, then lowest y value, and finally lowest z value.

So if I had this in the list:

• “Stone”, -20, 30, 15
• “Slope”, -20, 20, 50
• “Stone”, 40, 5, 0
• “Slope”, -20, 20, 10

It would end up like this:

• “Slope”, -20, 20, 10
• “Slope”, -20, 20, 50
• “Stone”, -20, 30, 15
• “Stone”, 40, 5, 0

Try to keep in mind I’m still not that good at Unity so if you can, try to provide some explanation on what the code is doing. Also I prefer C#.

Your block class will need to have a CompareTo method. It would probably look something like this:

``````public int CompareTo(object otherObject)
{
Block otherBlock = (Block) otherObject;

if(this.xLocation < otherBlock.xLocation)
{
return -1;
}
else if(this.xLocation > otherBlock.xLocation)
{
return 1;
}

//the x matched, so lets check y
if(this.yLocation < otherBlock.yLocation)
{
return -1;
}
else if(this.yLocation > otherBlock.yLocation)
{
return 1;
}

//the x and y matched, so lets check z
if(this.zLocation < otherBlock.zLocation)
{
return -1;
}
else if(this.zLocation > otherBlock.zLocation)
{
return 1;
}

//everything matched, the two blocks are equal
return 0;

}
``````

Then you could have an list of Blocks and just call Sort() on the list. If you need more details on implementing IComparable I’d check out this tutorial:

http://www.codeproject.com/Articles/42839/Sorting-Lists-using-IComparable-and-IComparer-Inte