My question is about the IComparer interface, I never worked with it before, so I hope you can help me set up everything right.
I have to use the interface to sort an list of own objects by the exact sequence of another List<int>.
I couldn’t find anything usefull with that problem on the net, everything I found were linq statements, that I can not use.
Here is the example code:
public class What : IComparer<What>
{
public int ID { get; set; }
public string Ever { get; set; }
public What(int x_ID, string x_Ever)
{
ID = x_ID;
Ever = x_Ever;
}
public int Compare(What x, What y)
{
return x.ID.CompareTo(y.ID);
}
}
Some data to work with:
List<What> WhatList = new List<What>()
{
new What(4, "there"),
new What(7, "are"),
new What(2, "doing"),
new What(12, "you"),
new What(78, "Hey"),
new What(63, "?")
};
And the list with the correct order:
List<int> OrderByList = new List<int>() { 78, 4, 63, 7, 12, 2 };
So now how can I tell IComparer to sort by the OrderByList?
I really got no clue how to do that, I know this would be pretty easy with linq, but I don’t have the opportunity to use it.
There are a few tings wrong with your code as it currently stands. If you look at the docs for
IComparer<T>you’ll see that theTis what you’re saying you are going to compare. In your code this isTestbut you go on to code for comparisons ofWhat– this means that your code will not compile. See here – error message is:With all that said and done, you should implement a
WhatComparer:And use that for ordering:
Live example: http://rextester.com/BZKO33641