0

Can someone please explain how i can possibly sort a linked-list by an object name alphabetically.

 //so lets say i have an Animal:
        public Animal()
        {
            name = null;
            age = 0;
            mass = 0;
        }

and wanna create random objects of this animal in main(), and insert them to a linked-list randomly. how can i then sort this linked-list of animals alphabetically by their name property :(

  • Does this answer your question? [Sorting a linked list](https://stackoverflow.com/questions/768095/sorting-a-linked-list) – Max Play May 20 '20 at 21:59
  • Using [LINQ](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/), you can create a new `List` that is sorted using the [`OrderBy` method](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderby?view=netframework-4.7.2#System_Linq_Enumerable_OrderBy__2_System_Collections_Generic_IEnumerable___0__System_Func___0___1__) and then convert back to a `List` with [`ToList`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.tolist?view=netframework-4.7.2). – NetMage May 20 '20 at 22:11

1 Answers1

0

Assuming that you are using List as a linked list, this should work.

animals = animals.OrderBy(animal => animal.name).ToList();
Vamsi
  • 1
  • 1