C# OrderBy in LINQ

Here are some examples of using OrderBy and related LINQ operators in C#:

Example 1: Using OrderBy in LINQ

List<int> numbers = new List<int> { 5, 3, 1, 4, 2 };

var sortedNumbers = numbers.OrderBy(n => n);

foreach (var number in sortedNumbers) {
    Console.WriteLine(number);
}

In this example, a List<int> is initialized with several integer values, and then the list is sorted in ascending order using the OrderBy method.

Example 2: Ordering a List in Descending Order

List<int> numbers = new List<int> { 5, 3, 1, 4, 2 };

var sortedNumbers = numbers.OrderByDescending(n => n);

foreach (var number in sortedNumbers) {
    Console.WriteLine(number);
}

In this example, a List<int> is initialized with several integer values, and then the list is sorted in descending order using the OrderByDescending method.

Example 3: Sorting a List by Multiple Criteria

List<(string, int)> people = new List<(string, int)> {
    ("Alice", 30),
    ("Bob", 20),
    ("Charlie", 30),
    ("Dave", 20),
    ("Eve", 40)
};

var sortedPeople = people.OrderBy(p => p.Item1)
                         .ThenByDescending(p => p.Item2);

foreach (var person in sortedPeople) {
    Console.WriteLine($"{person.Item1}, {person.Item2}");
}

In this example, a list of tuples containing names and ages is created, and then the list is sorted first by name in ascending order using the OrderBy method, and then by age in descending order using the ThenByDescending method.

Example 4: Filtering Null or Empty Values to Be Last in a List

List<string> names = new List<string> { "Alice", "Bob", null, "Charlie", "", "Eve" };

var sortedNames = names.OrderBy(n => string.IsNullOrEmpty(n))
                       .ThenBy(n => n);

foreach (var name in sortedNames) {
    Console.WriteLine(name);
}

In this example, a List<string> is initialized with several string values, including null and empty strings. The list is then sorted so that null and empty strings appear last, and all other values are sorted in ascending order using the OrderBy and ThenBy methods.

Example 5: Using OrderBy on a Dynamic List

var people = new List<dynamic> {
    new { Name = "Alice", Age = 30 },
    new { Name = "Bob", Age = 20 },
    new { Name = "Charlie", Age = 30 },
    new { Name = "Dave", Age = 20 },
    new { Name = "Eve", Age = 40 }
};

var sortedPeople = people.OrderBy("Name ASC")
                         .ThenBy("Age DESC");

foreach (var person in sortedPeople) {
    Console.WriteLine($"{person.Name}, {person.Age}");
}

In this example, a list of anonymous objects is created, with each object having Name and Age properties. The OrderBy and ThenBy methods are used to sort the list dynamically based on a string representation of the sort criteria. This is achieved using the System.Linq.Dynamic.Core library.

Example 6: Using Dynamic LINQ OrderBy on IEnumerable<T>

using System.Linq.Dynamic.Core;

var people = new List<dynamic> {
    new { Name = "Alice", Age = 30 },
    new { Name = "Bob", Age = 20 },
    new { Name = "Charlie", Age = 30 },
    new { Name = "Dave", Age = 20 },
    new { Name = "Eve", Age = 40 }
};

var sortedPeople = people.AsQueryable().OrderBy("Name ASC");

foreach (var person in sortedPeople) {
    Console.WriteLine($"{person.Name}, {person.Age}");
}

In this example, a list of anonymous objects is created, with each object having Name and Age properties. The OrderBy method is used to sort the list dynamically based on a string representation of the sort criteria. The AsQueryable method is used to convert the list to an IQueryable object, which allows the OrderBy method to be called with a string expression. The System.Linq.Dynamic.Core library is used to provide the dynamic LINQ functionality.

Note that the string expression passed to OrderBy must be in a specific format. The format is {property name} {direction}, where {property name} is the name of the property to sort by, and {direction} is either "ASC" for ascending order or "DESC" for descending order. Multiple sort criteria can be separated by commas. For example, "Name ASC, Age DESC" would sort the list by name in ascending order, and then by age in descending order.

  1. C# LINQ OrderBy example:

    var numbers = new List<int> { 5, 2, 8, 1, 9 };
    var orderedNumbers = numbers.OrderBy(num => num);
    
    foreach (var num in orderedNumbers)
    {
        Console.WriteLine(num);
    }
    
  2. LINQ OrderBy ascending and descending in C#:

    var numbers = new List<int> { 5, 2, 8, 1, 9 };
    var ascendingOrder = numbers.OrderBy(num => num);
    var descendingOrder = numbers.OrderByDescending(num => num);
    
  3. C# LINQ OrderBy multiple fields:

    var persons = new List<Person> { /* List of Person objects */ };
    var orderedPersons = persons.OrderBy(person => person.LastName).ThenBy(person => person.FirstName);
    
  4. Ordering strings and numbers with OrderBy in LINQ C#:

    var mixedList = new List<object> { "apple", 5, "orange", 2, "banana" };
    var orderedMixedList = mixedList.OrderBy(item => item.ToString());
    
  5. C# LINQ OrderByDescending example:

    var numbers = new List<int> { 5, 2, 8, 1, 9 };
    var descendingOrder = numbers.OrderByDescending(num => num);
    
  6. Ordering by custom criteria with OrderBy in LINQ C#:

    var persons = new List<Person> { /* List of Person objects */ };
    var customOrder = persons.OrderBy(person => person.Age % 10); // Custom sorting based on the last digit of age
    
  7. C# LINQ OrderBy using anonymous types:

    var persons = new List<Person> { /* List of Person objects */ };
    var orderedPersons = persons.OrderBy(person => new { person.LastName, person.FirstName });
    
  8. OrderBy with null values in LINQ C#:

    var persons = new List<Person?> { /* List of Person objects including nulls */ };
    var orderedPersons = persons.OrderBy(person => person?.LastName);
    
  9. C# LINQ OrderBy with custom comparer:

    var strings = new List<string> { "apple", "Orange", "banana" };
    var caseInsensitiveOrder = strings.OrderBy(s => s, StringComparer.OrdinalIgnoreCase);
    
  10. Ordering by multiple criteria with LINQ OrderBy in C#:

    var persons = new List<Person> { /* List of Person objects */ };
    var orderedPersons = persons.OrderBy(person => person.LastName).ThenBy(person => person.FirstName);
    
  11. C# LINQ OrderBy and Take example:

    var numbers = new List<int> { 5, 2, 8, 1, 9 };
    var topTwoNumbers = numbers.OrderBy(num => num).Take(2);
    
  12. C# LINQ OrderBy and Reverse:

    var numbers = new List<int> { 5, 2, 8, 1, 9 };
    var reversedOrder = numbers.OrderBy(num => num).Reverse();