6

Simple, I have a struct like this:

struct bla{
  string name;
  float depth;
}

I have an bla array, and I want to sort by depth, being the greatest depth first. What should the delegate do/return? I cant find any concrete example.

0

3 Answers 3

10

you find an example here: How would I sort through an array of structs?

you have two ways to do this, compact or expanded way:

struct bla
{
    public string name;
    public float depth;
}

bla[] theArray = new bla[5];

Array.Sort(theArray, (x, y) => x.depth.CompareTo(y.depth));

Array.Sort(theArray, delegate(bla bla1, bla bla2)
{
    return bla1.depth.CompareTo(bla2.depth);
});

swap x or y or bla1 and bla2 if the sort order is opposite of what you want.

8

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

bla[] blas = new[] { 
    new bla() { name = "3", depth = 3 }, 
    new bla() { name = "4", depth = 4 }, 
    new bla() { name = "2", depth = 2 }, 
    new bla() { name = "1", depth = 1 }, 
};

Array.Sort<bla>(blas, (x,y) => x.depth.CompareTo(y.depth));

On this way you sort the original array instead of creating new one.

4

using System.Linq;

blas.OrderByDescending(x=>x.depth)

or

Array.Sort(blas, (x, y) => y.depth.CompareTo(x.depth) );
3
  • Great, thanx, but would you give me an example with Array.sort? Aug 19, 2012 at 12:14
  • With Array.Sort it looks very similar: Array.Sort(array, (x, y) => x.depth.CompareTo(y)); Aug 19, 2012 at 12:20
  • 3
    @CodesInChaos any reason to be rude?
    – L.B
    Aug 19, 2012 at 12:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.