casillas
casillas

Reputation: 16813

Sort and Order Alphabetically

I have the following implementation and adding person to the list. However I would like to sort based on role then order based on alphabetical order. I wonder how it could be done in LINQ.

In other words, once sort and order is applied, I need to see all teacher item sequentially but alphabetically ordered.

class Program
{
    class Person
    {
        public Person(string id, string name, string role)
        {
            Id = id;
            Name = name;
        }
        public string Id { get; set; }
        public string Name { get; set; }
    }

    static void Main()
    {
        List<Person> persons = new List<Person>();
        persons.Add(new Person("P005", "Janson", "Teacher"));
        persons.Add(new Person("P137", "Aniket", "Student"));
        persons.Add(new Person("P002", "Aravind", "Teacher"));
        persons.Add(new Person("P007", "Kazhal", "Student"));
        persons.Add(new Person("P017", "Kamikaze", "Teacher"));
        persons.Add(new Person("P417", "Johnson", "Teacher"));
    }
}

Upvotes: 0

Views: 87

Answers (3)

Brett
Brett

Reputation: 56

First, add a Role property to your Person class. Then use a linq statement to sort and order the list.

var list = persons.OrderBy(x=>x.Role).ThenBy(x=>x.Name);

Upvotes: 1

Steve
Steve

Reputation: 11973

You can use ThenBy

var orderedList = persons.OrderBy(x=>x.Role).ThenBy(x=>x.Name); //You are missing a Role property

Upvotes: 4

Francisco Mu&#241;oz
Francisco Mu&#241;oz

Reputation: 19

persons.OrderBy(x =>x.Name).ToList();

Upvotes: -1

Related Questions