Ok… can you post your code? I think what you’re doing is this:
QueUnitComparer : IComparer
but it needs to be:
QueUnitComparer : IComparer
What is the DataType being returned by getWait? Also, you may be better avoiding the method call if all getWait is doing is returning the value of a property and do something like:
private int _wait;
public int Wait
{
public get { return _wait; }
private set { _wait = value; }
}
This will allow you to expose the property getter without exposing the setter and you’ll avoid the overhead of throwing another methodcall onto the stack. Then you can change everywhere you use “unit.getWait()” to just “unit.Wait”
Now for the code, here is the QueUnit I mocked up to test with:
namespace UnityTests
{
public class QueUnit
{
public int Wait;
public int getWait()
{
return Wait;
}
}
}
And I implemented the IComparer with the following… you should be able to copy this code (everything inside the Namespace brackets) and it will work:
using System.Collections.Generic;
namespace UnityTests
{
public class QueUnitComparer : IComparer<QueUnit>
{
public int Compare(QueUnit a, QueUnit b)
{
var waitA = a.getWait();
var waitB = b.getWait();
if (waitA > waitB)
return 1;
return -1;
}
}
}
Now here is the test that I used. It is the “Progam.cs” if a Console app, but you could copy everything inside the Main method and use it (except for the Console.WriteLine stuff):
using System;
using System.Collections.Generic;
using UnityTests;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
var list = new List<QueUnit>();
var rnd = new Random();
for (var i = 0; i < 100; i++)
{
list.Add(new QueUnit { Wait = rnd.Next(0, 9999)});
}
list.Sort(new QueUnitComparer());
foreach (var q in list)
{
Console.WriteLine(q.getWait());
}
Console.ReadKey();
}
}
}
How here’s something to keep in mind… I’m not sure how often or where all you’re doing the sorting. This method of sorting will actually physically re-order your list. You could also use LINQ like this:
foreach(var unit in unitList.OrderBy(q => q.getWait())
{
//Output your stuff
}
This will actually just get an enumerator over your collection and allow you to access it in order without physically re-ordering the list. There are pros and cons to each approach. One is physically reordering the lists which will cause fluctuations in memory allocation as it creates a new list comprised of the values from the old one, but then again you’re only sorting it when you absolutely need to. The second method (using LINQ) only creates an enumerator, but you could potentially be doing that sorting over and over and over. You could also add .ToList() to the end of your OrderBy and it will give the physically reordered list:
unitList = unitList.OrderBy(q => q.getWait()).ToList();
This does essentially the same as Sort but may still reorder equal values (I’m not sure if this behavior should actually be happening).