views:

86

answers:

5

For example, I have an array of floating point numbers:

float[] numbers = new float[] { 1, 34, 65, 23, 56, 8, 5, 3, 234 };

If I use:

Array.Sort(numbers);

Then the array is sorted by the size of the number.

I want to sort the numbers by another criteria, so element A should go before element B if f(A) < f(B), rather than the usual of A < B.

So, for example, If I want to sort them according to there value modulo 5. The array would become:

5, 65, 1, 56, 3, 8, 23, 34, 234

I think it can be done through LINQ, but I'm not sure how.

A: 

Have a look at IComparer ;-) and let an List sort the elements for you with your custom comparer.

Oliver Hanappi
+4  A: 

You can use the Comparison<T> overload of Array.Sort:

Array.Sort(numbers, (a,b) => (a % 5).CompareTo(b % 5));

Comparison<T> is just a delegate, so you can use lambdas / anonymous methods. It's not LINQ, but I think it's what you meant.

Richard Szalay
+7  A: 

I want to sort the numbers by another criteria, so element A should go before element B if f(A) < f(B)

numbers.OrderBy(f);
sepp2k
+1. Enumerable.OrderBy docs can be found here - http://msdn.microsoft.com/en-us/library/bb534966.aspx
Richard Szalay
Implementation for your requirement using Enumerable.OrderBy would be `numbers.OrderBy(f => f % 5);`
Richard Szalay
A: 

Using LINQ:

var result = from n in numbers orderby n % 5, n select n;
var sortedNumbers = result.ToArray();

Alternately:

var result = numbers.OrderBy(n => n % 5).ThenBy(n => n);

Ordering by mod 5, then by the number yields the results in the order you specified.

Ahmad Mageed
A: 

More Brute even! I suggest you to make an Array of f(x) and then sort on that!

HJ42