- Home /
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#.
Thanks in advance!
Answer by LessThanEpic · Jan 27, 2015 at 09:58 PM
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
Thanks! That looks like it should do what I want.
I'm getting a weird error message when I try the code: Assets/Scripts/Editor Scripts/EditorButtons.cs(7,14): error CS0535: Block' does not implement interface member
System.IComparable.CompareTo(Block)'
Any ideas?
Change your method signature from
public int CompareTo(Object otherBlock)
to
public int CompareTo(Block otherBlock)
Ok that bug was fixed, but now I have a new problem. I want to be able to add objects to a new list via button. Can I create a list in one function and add to it in another?
Never $$anonymous$$d, I just made the variable at the beginning of the class.
Your answer
![](https://koobas.hobune.stream/wayback/20220613181706im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Find index of item in list 1 Answer
Sorting a List of Dictionaries in C#? 4 Answers
Sort list game objects based on name 3 Answers