public class SortDistance : IComparer<EnemyInfo>
{
public int Compare(EnemyInfo a, EnemyInfo b)
{
//Sort descending
if (a.distance < b.distance) {return 1;}
else if (a.distance > b.distance) {return -1;}
else {return 0;}
}
}
And:
public class SortDistance : IComparer<EnemyInfo>
{
public int Compare(EnemyInfo a, EnemyInfo b)
{
//Sort ascending
return Comparer<float>.Default.Compare(a.distance, b.distance);
}
}
Other than sorting in opposite directions they seem to do the same thing? What is the difference?
Another question, I also have an “inSight” bool in the EnemyInfo constructor. Instead of sorting all the elements by distance. Can I sort only the elements where inSight = true? Would the if statement be placed in the SortDistance class? or in the method where I invoke Sort?
In most cases the comparison boils down to some kind of primitive type. Those usually have a CompareTo method. So you could simply do
return a.distance.CompareTo(b.distance);
if you want to sort them in reverse order, just swap a and b.
There’s no real difference between your first and second implementation besides that you reversed the sorting order.
About your second question: That doesn’t make much sense. When you sort a List or generally a collection of objects you don’t remove or add elements. They are simply sorted. A comparer just tells the sorting algorithm if, when comparing two elements, one element should come before or after the other or if it doesn’t matter.
In most cases it doesn’t make sense to create a seperate IComparer class. If you just want to be able to sort the elements, your EnemyInfo class could implement the IComparable interface. That way you can define a default sorting for your class. If you need a specific sorting order, you can simply use lambda expressions:
If you want to remove certain elements from a collection you can use linq. For example:
using System,Linq;
//...
var inSightSorted = list.Where(a=>a.inSight).Sort( (a,b)=>a.distance.CompareTo(b.distance) ).ToList();
In this case we create a new list out of the old one, we remove all elements where inSight is false and sort the resulting enumeration by distance all in just one line ^^.