2

I'm doing some exercise on Unity/C#, and for one of them I have a list that contain some inherited classes.

    public List<Item> items = new List<Item>();

each Item is an inherited class like PowerUp,ConceptArt,Bonus who all iherit from Item...

I would like to, sort that list using the name of the item class.

Basically if i have list

myList = { Bonus,ConceptArt, PowerUp, PowerUp,ConceptArt }

if I sort it, the output would be :

myList = { Bonus,ConceptArt, ConceptArt, PowerUp,PowerUp}

How do I do that?

I don't know if I explained myself clearly. If i need to edit, tell me :)

thx :)

Noxious Reptile
  • 838
  • 1
  • 7
  • 24
Crocsx
  • 2,534
  • 1
  • 28
  • 50

2 Answers2

2

Try this:

items = items.OrderBy(x => x.GetType().Name).ToList();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
2

To sort in place, without creating a new list:

  myList.Sort((Comparison<Item>) 
    ((left, right) => String.Compare(left.GetType().Name, right.GetType().Name)));

To check/test:

  String report = String.Join(", ", myList
    .Select(item => item.GetType().Name));

  Console.Write(report);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215