- Home /
Orderrring a List Ascending or Descending C# Advanced
Hey guys I am wanting to create an array with class this is my class
[System.Serializable]
public class Objects{
public String Name;
public float Value
}
and i have this variable
public Objects[] ObjectsList;
Now I need two function that orders the list
public enum order {ascending, descending}
public enum by {string, float}
public void Order (order Order, by By) {
// this function has to order ascending or descending by string or float.
// string = Name
// float = value
}
How can i do this? I have seen Array.Sort, but I am not sure, Can anyone help me please? Thanks see you, byeeee!
Answer by Julien-Lynge · Sep 25, 2012 at 05:34 PM
This really isn't anything Unity specific - if you want to know how to sort a list in C#, try googling it. There are many posts out there, for instance this one which appeared first in google for me:
Thanks, but this is not really what i am looking for, i have 2 variables, and i need to sort the list by one.
The URL Julien posted has most of the information you need. Look at the LINQ example in particular. If that doesn't help then google for LINQ and go from there.
And sorry for nit-picking, but "Objects" is not a good name for a class.
It' s oke, I will study them. Yeah you are right, Objects is not a good name for class it continue to confuse with Object, (System.Object)... See you byeee!
Answer by jacksparrow · Sep 25, 2012 at 07:11 PM
You can use a delegate to specify how to sort. Like this:
Things[] thingArray = new Things[3];
public enum order {ascending, descending};
public enum byvar {bystring, byfloat};
thingArray[0] = new Things("betty",1);
thingArray[1] = new Things("catherine",2);
thingArray[2] = new Things("abel",3);
void mysort(order Order, byvar By) {
if (Order == order.ascending) {
if (By == byvar.bystring) {
System.Array.Sort(thingArray, delegate(Things thing1, Things thing2) {
return thing1.tname.CompareTo(thing2.tname);
});
}
else if (By == byvar.byfloat) {
System.Array.Sort(thingArray, delegate(Things thing1, Things thing2) {
return thing1.number.CompareTo(thing2.number);
});
}
}
else {
if (By == byvar.bystring) {
System.Array.Sort(thingArray, delegate(Things thing1, Things thing2) {
return thing2.tname.CompareTo(thing1.tname);
});
}
else if (By == byvar.byfloat) {
System.Array.Sort(thingArray, delegate(Things thing1, Things thing2) {
return thing2.number.CompareTo(thing1.number);
});
}
}
}
Thanks, this is looking good, but can you explain this? because I don't know what to put on delegate (Things thing1, Things thing2). Thank you so much for the script, i think hat this might help me, if i can resolve the problem of Things thingX
Just use your Objects (and the appropriate variable names 'Name' and 'value') in place of the 'Things' with 'tname' and 'number'.
So you suggest me: delegate (Objects name, Objects value) right? but what is thing1.tname -> name.tname????