OrderBy() sorts the elements in the source sequence based on a key value. The examples below demonstrate how this works
List<string> strings =newList<string> { "first","then","and then","finally" };// Sort the strings by their length// Will contain { "then", "first", "finally", "and then" }IEnumerable<string> result =strings.OrderBy(str =>str.Length);
ThenBy() method
We can have two level ordering as shown below
classProgram{classStudent {publicstring Name { get; } //Propertypublicstring City { get; }publicStudent(string name,string city) { Name = name; City = city; } }staticvoidMain() { //Object initialization syntaxList<Student> students =newList<Student>() {newStudent("Sam","Mysore"),newStudent("Ted","Delhi"),newStudent("Sam","Bangalore"),newStudent("Raj","Mumbai"),newStudent("Adhin","Hyderabad"),newStudent("Raj","Indore"),newStudent("Bhuvan","Chennai"),newStudent("Sam","Banaras"), };var res =students.OrderBy(s =>s.Name).ThenBy(s =>s.City);foreach (var s in res)Console.WriteLine(s.Name+" "+s.City);Console.ReadKey(); }}
There is no Sort()
If you want to sort the elements within a sequence, but we achieve the same using the query below
List<string> strings =newList<string>(){ "first","then","and then","finally" };// Sort the strings in alphabetical order// Will contain { "and then", "finally", "first", "then" }IEnumerable<string> result =strings.OrderBy(str => str); //strange?!foreach (string str in result)Console.WriteLine(str);
Can you try these for an Employee(int id, string name, int age) object?