How to use Array.sort to sort an array of structs, by a specific element

后端 未结 3 529

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

3条回答
  •  旧巷少年郎
    2021-01-14 01:26

    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.

提交回复
热议问题