Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

sorting

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.

like image 744
Icebone1000 Avatar asked Aug 19 '12 12:08

Icebone1000


People also ask

How do you sort a specific part of an array?

Arrays. sort() method can be used to sort a subset of the array elements in Java. This method has three arguments i.e. the array to be sorted, the index of the first element of the subset (included in the sorted elements) and the index of the last element of the subset (excluded from the sorted elements).

How do I sort an array from a specific index?

To sort an array only in specified index range, you can call Arrays. sort() method and pass the arguments: array, starting-index and to-index to the method. arr is the array of elements.

How do you sort an array of structs in go?

Use the function sort. Slice . It sorts a slice using a provided function less(i, j int) bool . To sort the slice while keeping the original order of equal elements, use sort.

How do you sort the elements in the array syntax of the array?

It means that the array sorts elements in the ascending order by using the sort() method, after that the reverseOrder() method reverses the natural ordering, and we get the sorted array in descending order. Syntax: public static <T> Comparator<T> reverseOrder()


2 Answers

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.

like image 139
Davide Piras Avatar answered Nov 15 '22 05:11

Davide Piras


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.

like image 26
Tim Schmelter Avatar answered Nov 15 '22 06:11

Tim Schmelter