- Home /
List.Sort with IComparer
i created a list but i want to sort it with a custom IComparer... the IComparer class is this
public class Comp : IComparer<int>
{
public int Compare (int x, int y)
{
if (x == null) {
if (y == null) {
return 0;
} else {
return 1;
}
} else {
if (y == null) {
return -1;
} else {
int difference = x.CompareTo (y);
if (difference != 0) {
return difference;
} else {
return 0;
}
}
}
}
}
Now in the same script I call a function that Add objects in the list, but at the end I want sort the list
Comp comparer = new Comp ();
foreach (GameObject item in items)
{
int i = Array.IndexOf (items, item);
ItemData itemScript = item.GetComponent <ItemData> ();
yield return itemScript.itemState;
itemSt.Add (new ItemStat (itemScript.ID, itemScript.itemState, item.name));
if (items [i].name == itemSt [i].Name && itemSt [i].State == "Destroyed")
{
Destroy (item.gameObject, 0.0F);
}
}
itemSt.Sort (comparer);
But the itemSt.Sort (comparer); line give two errors:
The best overloaded method match for System.Collections.Generic.List<ItemStat>.Sort(System.Collections.Generic.IComparer<ItemStat>) has some invalid arguments
Argument #1' cannot convert Comp' expression to type System.Collections.Generic.IComparer<ItemStat>'
I don't understand the problem... why i can't sort this list that contains variables from ItemStat class?
Answer by Bunny83 · Jun 01, 2016 at 05:39 PM
You create a comparer for the type "int" but you want to compare "ItemStat" objects. That doesn't make much sense.
Your comparer should look like this:
public class Comp : IComparer<ItemStat>
{
public int Compare (ItemStat x, ItemStat y)
{
// your custom compare code here.
}
}
From your code it isn't clear what those ItemStat objects contain and based on what you want to sort them. So you have to implement the comparing code yourself or include how the ItemStat class looks like and how you want them to be sorted.
Yes, the problem was this... thanks
Now the script is:
public class Comp : IComparer<ItemStat>
{
public int Compare (ItemStat x, ItemStat y)
{
if (x == null) {
if (y == null) {
return 0;
} else {
return 1;
}
} else {
if (y == null) {
return -1;
} else {
int difference = x.ID.CompareTo(y.ID);
if (difference != 0) {
return difference;
} else {
return 0;
}
}
}
}
}
Answer by farhanblu · Jun 01, 2016 at 05:53 PM
If I were you, I would have a class (that I want sorted in list) implement IComparable interface. MSDN Reference
You could also consider using Linq if you want to avoid typing much code (i.e. implementing an interface for each comparable class).