List custom sorting - c#

I want to sort a custom list I have on a certain criteria. Every item in my list contains a property called "Status" which is a enumeration, shown below.
Empty = 0, Normal = 1, Aged = 2, Dead = 3
The values assigned above cannot be changed. When I sort on my Status property I would like the order to be as such Normal, Aged, Empty & Dead. I do not know how best to go about this?
Below is an example of a class I'm using for a different sorting issue. Not sure how I would 'convert' this class to solve my issue above?
public class SortOrders : IComparer<OrderBlocks.Order>
{
private bool _sortDescending;
public SortOrders(bool sortDescending)
{
this._sortDescending = sortDescending;
}
public SortOrders()
: this(false) // sort ascending by default
{
}
public int Compare(OrderBlocks.Order x, OrderBlocks.Order y)
{
if (this._sortDescending)
{
return y.StatusGood.CompareTo(x.StatusGood);
}
else
{
return x.StatusGood.CompareTo(y.StatusGood);
}
}
}

Here's how I would do it using Linq:
var sorted = myList.OrderBy(x =>
{
switch (x.Status)
{
case SomethingStatus.Normal:
return 0;
case SomethingStatus.Aged:
return 1;
case SomethingStatus.Empty:
return 2;
case SomethingStatus.Dead:
return 3;
default:
return 10;
}
});

The order by linq extension take a Func<TSource, TKey> keySelector, so you can pass a custom ordered method that return an int value base on the order you need:
public enum Status { Empty = 0, Normal = 1, Aged = 2, Dead = 3 }
public class Item
{
public Status Status { get; set; }
public int OrderedStatus
{
get
{
switch (this.Status)
{
case Status.Normal: return 0;
case Status.Aged: return 1;
case Status.Empty: return 2;
default: return 3; // case Status.Dead
}
}
}
public static IEnumerable<Item> OrderByStatus(IEnumerable<Item> items)
{
return items.OrderBy(item => item.OrderedStatus);
}
}

I would create a conversion function that StatusGood is passed through prior to comparing it, ie:
public static class StatusGoodExtensions
{
public static int OrderIndex(this StatusGood statusIn)
{
switch ( statusIn )
{
case StatusGood.Normal: return 0;
case StatusGood.Aged: return 1;
case StatusGood.Empty: return 2;
case StatusGood.Dead: return 3;
}
throw new NotImplementedException(statusIn.ToString());
}
}
using in the comparison, like so:
return x.StatusGood.OrderIndex().CompareTo(y.StatusGood.OrderIndex());
By having an extension method, the logic to return the order is cleanly separated from the sorting, and could be tested or re-used elsewhere.

There are lots ways to do it using OrderBy:
Chaining OrderBy and ThenBy calls together with your custom order:
var ordered = list.OrderBy(f1 => f1.Status == 3)
.ThenBy(f2 => f2.Status == 0)
.ThenBy(f3 => f3.Status == 2)
.ThenBy(f4 => f4.Status == 1).ToList();
Or use a delegate switch/case inline:
var ordered2 = list.OrderBy(foo =>
{
switch (foo.Status)
{
case (int)Status.Normal:
return 0;
case (int)Status.Aged:
return 1;
case (int)Status.Empty:
return 2;
case (int)Status.Dead:
return 3;
default:
return 0;
}
}).ToList();
Both give the same results. The first method uses the enum values you already have, the second looks at the enum value and returns a different integer to be used for comparison.

Related

Implementation of IEnumerable and IEnumerator in custom object, return the same data when called multiple times by LINQ with a different predicate

I wanted to be able to use LINQ queries on a custom object that does not use typical collections but nevertheless stores data in a sequential manner. The object is of type XTable that contains a collection of XRows and I have the following code that implements IEnumerable and IEnumerator.
public class EnumerableXTable : IEnumerable<XRow>
{
private readonly XTable _xTable;
public EnumerableXTable(XTable xTable)
{
_xTable=xTable;
}
IEnumerator<XRow> IEnumerable<XRow>.GetEnumerator()
{
return new XTableEnumerator(_xTable);
}
public IEnumerator GetEnumerator()
{
return new XTableEnumerator(_xTable);
}
}
public class XTableEnumerator : IEnumerator<XRow>
{
private readonly XTable _xTable;
private int _index = -1;
public XTableEnumerator(XTable xTable)
{
_xTable=xTable;
}
public void Dispose()
{
}
public bool MoveNext()
{
_index++;
if (_index == _xTable.Count) return false;
_xTable.Current.RecNo = _index;
return true;
}
public void Reset()
{
throw new NotImplementedException("IEnumerator Reset Method not implemented");
}
public XRow Current => _xTable.Current;
object IEnumerator.Current => Current;
}
public static EnumerableXTable AsEnumerable(this XTable xTable)
{
return new EnumerableXTable(xTable);
}
If I run the below code:
XTable t = GetXTable();
var xRow1 = t.AsEnumerable().First(xRow => xRow.Get<int>("CCCIntaleId") == 462);
var xRow2 = t.AsEnumerable().First(row => row.Get<int>("CCCIntaleId") == 465);
xRow1 and xRow2 are the exact same row, and according to the predicate, they should be different. If I set breakpoints, then when I break after the first statement, xRow1 has the correct value and if I break after the second statement, xRow2 has the correct value and now xRow1 is the value of xRow2. It looks like there is some form of deferred execution although I think that when calling First(), execution should be immediate. The following code returns the correct results on recNo1 and recNo2:
XTable t = GetXTable();
var xRow1 = t.AsEnumerable().First(xRow => xRow.Get<int>("CCCIntaleId") == 462);
int recNo1 = xRow1.RecNo;
var xRow2 = t.AsEnumerable().First(row => row.Get<int>("CCCIntaleId") == 465);
int recNo2 = xRow2.RecNo;
Furthermore, if I run the same code on a DataTable with the same structure as follows:
var row1 = datatable.AsEnumerable().First(row => row.Field<int>("CCCIntaleId") == 462);
var row2 = dd.AsEnumerable().First(row => row.Field<int>("CCCIntaleId") == 465);
the results I get are as expected. Is there anything wrong on my implementation of IEnumerator?
The solution was given in the comments. The problem was that _xTable.Current returns the same object everytime, with a different indexer. Thus, both xRow1 and xRow2 refer to the same object and at the end, both objects point to the values dictated by the indexer.

How to sort List<T> in c#

I've got a List<Card>, and I want to sort these cards
So, I'm looking for a method to sort them with different criterias, like their ID, their Name ...
public class Card : IComparer
{
public string ID;
public string Name;
public int CompareId(object firstCard, object secondCard)
{
Card c1 = (Card)firstCard;
Card c2 = (Card)secondCard;
return c1.Id.CompareTo(c2.Id);
}
}
But then, visual studio sent me an error :
'Card' does not implement interface member 'IComparer<Card>.Compare(Card, Card)'
You, probably, want to have your class Comparable not a Comparator
public class Card : IComparable<Card>
{
public string ID;
public string Name;
public int CompareTo(Card other)
{
if (null == other)
return 1;
// string.Compare is safe when Id is null
return string.Compare(this.Id, other.Id);
}
}
then
List<Card> myList = ...
myList.Sort();
Edit: If you want to have several criteria to choose from, you have to implement several Comparers as separated classes, e.g.
public sealed class CardByIdComparer : IComparer<Card>
{
public int Compare(Card x, Card y)
{
if (object.ReferenceEquals(x, y))
return 0;
else if (null == x)
return -1;
else if (null == y)
return 1;
else
return string.Compare(x.Id, y.Id);
}
}
and when sorting provide the required:
List<Card> myList = ...
myList.Sort(new CardByIdComparer());
Edit 2: (inspired by spender's library). If you want to combine several comparers into one (i.e. use comparer1, on tie - comparer2 etc.)
public sealed class ComparerCombined<T> : IComparer<T> {
private IComparer<T>[] m_Comparers;
public ComparerCombined(params IComparer<T>[] comparers) {
if (null == comparers)
throw new ArgumentNullException(nameof(comparers));
m_Comparers = comparers
.Select(item => item == null ? Comparer<T>.Default : item)
.Where(item => item != null)
.Distinct()
.ToArray();
}
public int Compare(T x, T y) {
if (object.ReferenceEquals(x, y))
return 0;
else if (null == x)
return -1;
else if (null == y)
return 1;
foreach (var comparer in m_Comparers) {
int result = comparer.Compare(x, y);
if (result != 0)
return result;
}
return 0;
}
}
usage:
myList.Sort(new ComparerCombined(
new CardByIdComparer(), // Sort By Id
new CardByNameComparer() // On tie (equal Id's) sort by name
));
The easiest way You can use Linq:
List<Card> objSortedList = objListObject.OrderBy(o=>o.ID).ToList();
or
List<Card> objSortedList = objListObject.OrderByDescending(o=>o.ID).ToList();
Good examples for demonstrate the concept of
List<T>.Sort(IComparer <T>) method check the link please.
IComparer<T> in this example compare method used for strings IComparer<T>
but you can use this for ID(int) too.
using System;
using System.Collections.Generic;
class GFG : IComparer<string>
{
public int Compare(string x, string y)
{
if (x == null || y == null)
{
return 0;
}
// "CompareTo()" method
return x.CompareTo(y);
}
}
public class geek
{
public static void Main()
{
List<string> list1 = new List<string>();
// list elements
list1.Add("C++");
list1.Add("Java");
list1.Add("C");
list1.Add("Python");
list1.Add("HTML");
list1.Add("CSS");
list1.Add("Scala");
list1.Add("Ruby");
list1.Add("Perl");
int range = 4;
GFG gg = new GFG();
Console.WriteLine("\nSort a range with comparer:");
// sort the list within a
// range of index 1 to 4
// where range = 4
list1.Sort(1, range, gg);
Console.WriteLine("\nBinarySearch and Insert Dart");
// Binary Search and storing
// index value to "index"
int index = list1.BinarySearch(0, range,
"Dart", gg);
if (index < 0)
{
list1.Insert(~index, "Dart");
range++;
}
}
}
You need to implement IComparer
public int Compare(Card card1, Card card2)
{
if (card1.ID > card2.ID)
return 1; //move card1 up
if (card2.ID < card1.ID)
return -1; //move card2 up
return 0; //do nothing
}

How to keep one of duplicate entries in list<T>

I have a list and in the list there are multiple entries. If the list contains an entry that is duplicated then I want to only keep one of the duplicates.
I've tried many things, the list.Distinct().ToList() and this does not remove the duplicate entry, I do not want to override the classes Equals method, so is there a way outside of that.
I've also done this method which seems to again, not remove the duplicate entry as it does not consider object a == object b.
private void removeDupes(List<Bookings> list)
{
int duplicates = 0;
int previousIndex = 0;
for (int i = 0; i < list.Count; i++)
{
bool duplicateFound = false;
for (int x = 0; x < i; x++)
{
if (list[i] == list[x])
{
duplicateFound = true;
duplicates++;
break;
}
}
if (duplicateFound == false)
{
list[previousIndex] = list[i];
previousIndex++;
}
}
}
There is another overload of the Distinct LINQ extension method that also takes an IEqualityComparer as an argument (see this link). So you'd need to create a class that implements IEqualityComparer<Bookings> and supply an instance of it to the Distinct-method. This way, you do not need to override the Equals method of the type.
The rules on whether two objects are equal to one another are implemented in the EqualityComparer.
As an alternative, you can use a HashSet and supply the EqualityComparer in the constructor.
A possible solution for your problem in order of Markus answer might look like this:
public class Booking
{
public Booking(int id, float amount)
{
BookingId = id;
BookingAmount = amount;
}
public int BookingId { get; }
public float BookingAmount { get; }
}
public class BookingComparer : IEqualityComparer<Booking>
{
public bool Equals(Booking x, Booking y)
{
return (x.BookingAmount == y.BookingAmount) && (x.BookingId == y.BookingId);
}
public int GetHashCode(Booking obj)
{
return obj.BookingId.GetHashCode()*17 + obj.BookingAmount.GetHashCode()*17;
}
}
internal class Program
{
private static void Main(string[] args)
{
var booking1 = new Booking(1, 12);
var booking2 = new Booking(1, 12);
var bookings = new List<Booking>();
bookings.Add(booking1);
bookings.Add(booking2);
var result = bookings.Distinct(new BookingComparer()).ToList();
}
}

Sort a List<T> by enum where enum is out of order

I have a List of messages.
Each message has a type.
public enum MessageType
{
Foo = 0,
Bar = 1,
Boo = 2,
Doo = 3
}
The enum names are arbitrary and cannot be changed.
I need to return the list sorted as: Boo, Bar, Foo, Doo
My current solution is to create a tempList, add the values in the order I want, return the new list.
List<Message> tempList = new List<Message>();
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Boo));
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Bar));
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Foo));
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Doo));
messageList = tempList;
How can I do this with an IComparer?
An alternative to using IComparer would be to build an ordering dictionary.
var orderMap = new Dictionary<MessageType, int>() {
{ MessageType.Boo, 0 },
{ MessageType.Bar, 1 },
{ MessageType.Foo, 2 },
{ MessageType.Doo, 3 }
};
var orderedList = messageList.OrderBy(m => orderMap[m.MessageType]);
So, let's write our own comparer:
public class MyMessageComparer : IComparer<MessageType> {
protected IList<MessageType> orderedTypes {get; set;}
public MyMessageComparer() {
// you can reorder it's all as you want
orderedTypes = new List<MessageType>() {
MessageType.Boo,
MessageType.Bar,
MessageType.Foo,
MessageType.Doo,
};
}
public int Compare(MessageType x, MessageType y) {
var xIndex = orderedTypes.IndexOf(x);
var yIndex = orderedTypes.IndexOf(y);
return xIndex.CompareTo(yIndex);
}
};
How to use:
messages.OrderBy(m => m.MessageType, new MyMessageComparer())
There is a easier way: just create ordereTypes list and use another overload of OrderBy:
var orderedTypes = new List<MessageType>() {
MessageType.Boo,
MessageType.Bar,
MessageType.Foo,
MessageType.Doo,
};
messages.OrderBy(m => orderedTypes.IndexOf(m.MessageType)).ToList();
Hm.. Let's try to take advantages from writing our own IComparer. Idea: write it like our last example but in some other semantic. Like this:
messages.OrderBy(
m => m.MessageType,
new EnumComparer<MessageType>() {
MessageType.Boo,
MessageType.Foo }
);
Or this:
messages.OrderBy(m => m.MessageType, EnumComparer<MessageType>());
Okay, so what we need. Our own comparer:
Must accept enum as generic type (how to solve)
Must be usable with collection initializer syntax (how to)
Must sort by default order, when we have no enum values in our comparer (or some enum values aren't in our comparer)
So, here is the code:
public class EnumComparer<TEnum>: IComparer<TEnum>, IEnumerable<TEnum> where TEnum: struct, IConvertible {
protected static IList<TEnum> TypicalValues { get; set; }
protected IList<TEnum> _reorderedValues;
protected IList<TEnum> ReorderedValues {
get { return _reorderedValues.Any() ? _reorderedValues : TypicalValues; }
set { _reorderedValues = value; }
}
static EnumComparer() {
if (!typeof(TEnum).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
TypicalValues = new List<TEnum>();
foreach (TEnum value in Enum.GetValues(typeof(TEnum))) {
TypicalValues.Add(value);
};
}
public EnumComparer(IList<TEnum> reorderedValues = null) {
if (_reorderedValues == null ) {
_reorderedValues = new List<TEnum>();
return;
}
_reorderedValues = reorderedValues;
}
public void Add(TEnum value) {
if (_reorderedValues.Contains(value))
return;
_reorderedValues.Add(value);
}
public int Compare(TEnum x, TEnum y) {
var xIndex = ReorderedValues.IndexOf(x);
var yIndex = ReorderedValues.IndexOf(y);
// no such enums in our order list:
// so this enum values must be in the end
// and must be ordered between themselves by default
if (xIndex == -1) {
if (yIndex == -1) {
xIndex = TypicalValues.IndexOf(x);
yIndex = TypicalValues.IndexOf(y);
return xIndex.CompareTo(yIndex);
}
return -1;
}
if (yIndex == -1) {
return -1; //
}
return xIndex.CompareTo(yIndex);
}
public void Clear() {
_reorderedValues = new List<TEnum>();
}
private IEnumerable<TEnum> GetEnumerable() {
return Enumerable.Concat(
ReorderedValues,
TypicalValues.Where(v => !ReorderedValues.Contains(v))
);
}
public IEnumerator<TEnum> GetEnumerator() {
return GetEnumerable().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerable().GetEnumerator();
}
}
So, well, let's make sorting more faster. We need to override default OrderBy method for our enums:
public static class LinqEnumExtensions
{
public static IEnumerable<TSource> OrderBy<TSource, TEnum>(this IEnumerable<TSource> source, Func<TSource, TEnum> selector, EnumComparer<TEnum> enumComparer) where TEnum : struct, IConvertible
{
foreach (var enumValue in enumComparer)
{
foreach (var sourceElement in source.Where(item => selector(item).Equals(enumValue)))
{
yield return sourceElement;
}
}
}
}
Yeah, that's lazy. You can google how yield works. Well, let's test speed. Simple benchmark: http://pastebin.com/P8qaU20Y. Result for n = 1000000;
Enumerable orderBy, elementAt: 00:00:04.5485845
Own orderBy, elementAt: 00:00:00.0040010
Enumerable orderBy, full sort: 00:00:04.6685977
Own orderBy, full sort: 00:00:00.4540575
We see, that our own orderBy by is more lazy that standart order by (yeah, it doesn't need to sort everything). And faster even for fullsort.
Problems in this code: it doesn't support ThenBy(). If you need this, you can write your own linq extension that returns IOrderedEnumerable There are a blog post series by Jon Skeet which goes into LINQ to Objects in some depth, providing a complete alternative implementation. The basis of IOrderedEnumerable is covered in part 26a and 26b, with more details and optimization in 26c and 26d.
Instead of using an IComparer, you could also use a SelectMany approach, which should have better performance for large message lists, if you have a fixed number of message types.
var messageTypeOrder = new [] {
MessageType.Boo,
MessageType.Bar,
MessageType.Foo,
MessageType.Doo,
};
List<Message> tempList = messageTypeOrder
.SelectMany(type => messageList.Where(m => m.MessageType == type))
.ToList();
You may avoid writing a completely new type just to implement IComparable. Use the Comparer class instead:
IComparer<Message> comparer = Comparer.Create<Message>((message) =>
{
// lambda that compares things
});
tempList.Sort(comparer);
You can build a mapping dictionary dynamically from the Enum values with LINQ like this:
var mappingDIctionary = new List<string>((string[])Enum.GetNames(typeof(Hexside)))
.OrderBy(label => label )
.Select((i,n) => new {Index=i, Label=n}).ToList();
Now any new values added to the Enum n future will automatically get properly mapped.
Also, if someone decides to renumber, refactor, or reorder the enumeration, everything is handled automatically.
Update:
As pointed out below, Alphabetical ordering was not called for; rather a semi- alphabetical ordering, so essentially random. Although not an answer to this particular question, this technique might be useful to future visitors, so I will leave it standing.
No need to have the mapping. This should give you the list and order based on the enum. You don't have to modify anything even when you change the enum's order or and new items...
var result = (from x in tempList
join y in Enum.GetValues(typeof(MessageType)).Cast<MessageType>()
on x equals y
orderby y
select y).ToList();
If you are about to get this working with Entity Framework (EF), you would have to spread out your enum in your OrderBy as such:
messageList.OrderBy(m =>
m.MessageType == MessageType.Boo ? 0 :
m.MessageType == MessageType.Bar ? 1 :
m.MessageType == MessageType.Foo ? 2 :
m.MessageType == MessageType.Doo ? 3 : 4
);
This creates a sub select with CASE WHEN, then ORDER BY on that temporary column.

Sort a list by reference C#

I have a List<Unit> where Unit contains Name and Value. In this object I store information about apparel sizes Name contains size names (S,M,L,XL..) and Value contains the quantity of that size.
This unit list is contained from a database, but the list comes in random order, so in the liste it might be like this:
Unit(M,3)
Unit(S,1)
Unit(XXL,2)
Unit(L,2)
I would like to sort the list so that it become more like this:
Unit(S,1)
Unit(M,3)
Unit(L,2)
Unit(XXLL,2)
I cant order on the string ASCE or DESC since it M comes before S and so on.
Then I thought I might create an reference Array with the correct order (XXS,XS,S,M,L,XL,XXL,XXXL), but how can I sort my list according to the reference.
Or are there other clever ways of doing this?
Update
Thanks for all good answers, I landed on the Enum solution, and it finally looks like this:
public class Unit
{
public Unit()
{
}
public Unit(string name, int value)
{
Value = value;
SizeCode = AssignSizeCode(name);
}
public SizeCode SizeCode { get; set; }
public int Value { get; set; }
private SizeCode AssignSizeCode(string name)
{
switch (name)
{
case "XXS":
return SizeCode.XXS;
case "XS":
return SizeCode.XS;
case "S":
return SizeCode.S;
case "M":
return SizeCode.M;
case "L":
return SizeCode.L;
case "XL":
return SizeCode.XL;
case "XXL":
return SizeCode.XXL;
case "XXXL":
return SizeCode.XXXL;
default:
return SizeCode.Unknown;
}
}
}
public enum SizeCode
{
XXS = 1,
XS = 2,
S = 3,
M = 4,
L = 5,
XL = 6,
XXL = 7,
XXXL = 8,
Unknown = 9
}
And I sort it like this:
units = units.OrderBy(x => (int)x.SizeCode).ToList();
Any comments, or things I can improve?
How about using a enum
public enum Size
{
Small = 1,
Medium = 2,
// etc
}
Then you can convert the enum value in Unit class to int and sort by the integer value.
Ok, I consider you should have OrderIndex column in your database and sort by that column.
the dirty way is to have your own class with interface : IComparer or do the same as delegate for sorting.
Check ICompararer in MSDN: http://msdn.microsoft.com/en-us/library/system.collections.icomparer.aspx
You can do exactly what MSDN suggest here:
// First, declare a few classes that implement the IComparer interface.
public class CompareShirtSize : IComparer<string>
{
// Because the class implements IComparer, it must define a
// Compare method. The method returns a signed integer that indicates
// whether s1 > s2 (return is greater than 0), s1 < s2 (return is negative),
// or s1 equals s2 (return value is 0). This Compare method compares strings.
public int Compare(string size1, string size2)
{
// Do size comarison here
return ConvertSizeToInt(size1) - ConvertSizeToInt(size2);
}
private int ConvertSizeToInt(string size)
{
switch (size)
{
case "XXS":
return 1;
case "XS":
return 2;
case "S":
return 3;
case "M":
return 4;
case "L":
return 5;
default:
// some error handling
}
}
// The following method tests the Compare methods defined in the previous classes.
public static void OrderByIComparer()
{
List<Unit> units;
// Sort the elements of the array alphabetically.
var sortedList = units.OrderBy(unit => unit.Size, new CompareShirtSize ());
}
You could add a Size property of type int in your class Unit. Then sort your list using this Size property.
public class Unit1
{
public Unit1(string name)
{
this.Name = name;
switch (this.Name)
{
case "XXS":
this.Size = 1;
break;
case "XS":
this.Size = 2;
break;
case "S":
this.Size = 3;
break;
case "M":
this.Size = 4;
break;
case "L":
this.Size = 5;
break;
}
}
public string Name { get; set; }
public int Size { get; private set; }
public int Value { get; set; }
}
private static void Main(string[] args)
{
List<Unit1> list1 = new List<Unit1>();
list1.Add(new Unit1("XS") { Value = 1 });
list1.Add(new Unit1("M") { Value = 1 });
list1.Add(new Unit1("S") { Value = 1 });
list1.Add(new Unit1("L") { Value = 1 });
var sortedList = list1.OrderBy(z => z.Size).ToList();
}
You simply need to use a Comparison Delegate. Firstly, make a function that just assigns a number to every size and then use that for comparison:
(I am not sure whether your sizes are stored as a String as an enum; but I would recommend storing them as an enum with the ordinal numbers in order of the sizes, increasing or decreasing. This will help make your comparison delegate faster and simpler).
public class ShirtSizeCompare {
private static int getIndex(Unit x) {
if(x == Null) { return -1; }
if(x.size == "S") {
return 0;
} else if(x.size == "M") {
return 1;
}
///...
}
private static int CompareShirts(Unit x, Unit y) {
int _x = getIndex(x);
int _y = getIndex(y);
if(_x < _y) {
return -1;
} else if(_x == _y) {
return 0;
} else {
return 1;
}
}
}
Then, simply use the Comparison delegate to sort the list:
List<Unit> unitList;
unitList.sort(CompareShirts);
The comparison delegate basically takes as input two variables x and y and returns:
<0 (if x < y)
>0 (if x > y)
0 (if x == y)
Check this page for more information: http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx

Categories

Resources