How to do custom Sorting in a List?

You’re still not using code tags… use code tags:

Also in your code you’re using linq to order the list and then generating a whole new list. Does it work? Yes. Is it the best way to go about it? Not particularly since you’re literally generating a whole new list.

As Nad_B pointed out it you’re not doing this often it may not matter. But if you do become concerned about it… as Kurt said list and array’s sort methods have overloads for sorting custom wise.

Here is the documentation for List.Sort (it appears ‘scripts’ in this case are in a List):

The documentation includes examples.

In your case something like:

lst.Sort((a, b) => a.Rarity.CompareTo(b.Rarity));

sort ascending by rarity

lst.Sort((a, b) => b.Rarity.CompareTo(a.Rarity));
//or
lst.Sort((a, b) => -a.Rarity.CompareTo(b.Rarity));

sorts descending by rarity

This will sort your list in place rather than creating a new list.

(also note how much easier the code is to read in code tags)

5 Likes