# Methods Ordering

## Methods for ordering the elements

### OrderBy() method

OrderBy() sorts the elements in the source sequence based on a key value. The examples below demonstrate how this works

```csharp
List<string> strings = new List<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

```csharp
class Program
{
    class Student
    {
        public string Name { get; } //Property
        public string City { get; }
        
        public Student(string name, string city)
        {
            Name = name;
            City = city;
        }
    }
    
    static void Main()
    {
        //Object initialization syntax
        List<Student> students = new List<Student>()
        {
            new Student("Sam","Mysore"),
            new Student("Ted","Delhi"),
            new Student("Sam","Bangalore"),            
            new Student("Raj","Mumbai"),
            new Student("Adhin","Hyderabad"),
            new Student("Raj","Indore"),            
            new Student("Bhuvan","Chennai"),
            new Student("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

```csharp
List<string> strings = new List<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?


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://raviram.gitbook.io/c-programing/linq/methods-ordering.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
