I was doing homework in C# that required sorting an array. I could sort an array of integers using
Array.sort<int>(a, delegate(int x, int y) { return y-x;});
However if i want to do it from certain position and certain length
Array.sort<int>(a, 0, m, delegate(int x, int y) { return y-x;});
I get compilation error: “Cannot convert anonymous method to type ‘System.Collections.Generic.IComparer’ because it is not a delegate type”.
I have solved the problem just by using
Array.sort<int>(a, 0, m);
and doing all other stuff backwards. Why it was giving me an error, and how can change it to work?
Thanks for help
The method the first example is calling has the signature:
The delegate you are using is for the Comparison. There is not an overload of
Array.Sortthat has a index, length and Comparison.The method you are trying to call has the following signature:
Note IComparer, not Comparison
If you need custom sorting. You will need to create a class that implements IComparer as this is what the 4th parameter is expecting.
Alternatively, try the
.OrderByDescendingextension method which is available when you includeusing System.Linq;