0
0
C Sharp (C#)programming~5 mins

OrderBy and sorting in C Sharp (C#)

Choose your learning style9 modes available
Introduction

We use OrderBy to arrange items in a list from smallest to largest or in a specific order. It helps us find things quickly and see data clearly.

When you want to show a list of names in alphabetical order.
When you need to sort numbers from lowest to highest.
When you want to organize products by price from cheapest to most expensive.
When you want to display dates from earliest to latest.
When you want to sort students by their grades.
Syntax
C Sharp (C#)
var sortedList = list.OrderBy(item => item.Property);
OrderBy returns a new sorted sequence; it does not change the original list.
You can use OrderBy with any property or value you want to sort by.
Examples
This sorts a list of numbers from smallest to largest.
C Sharp (C#)
var numbers = new List<int> { 5, 3, 8, 1 };
var sortedNumbers = numbers.OrderBy(n => n);
This sorts a list of names alphabetically.
C Sharp (C#)
var names = new List<string> { "Bob", "Alice", "Eve" };
var sortedNames = names.OrderBy(name => name);
This sorts a list of people by their age from youngest to oldest.
C Sharp (C#)
var people = new List<Person> {
    new Person { Name = "Bob", Age = 30 },
    new Person { Name = "Alice", Age = 25 }
};
var sortedByAge = people.OrderBy(p => p.Age);
Sample Program

This program creates a list of people and sorts them by their names alphabetically using OrderBy. Then it prints each person's name and age.

C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Linq;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        var people = new List<Person>
        {
            new Person { Name = "Charlie", Age = 35 },
            new Person { Name = "Alice", Age = 25 },
            new Person { Name = "Bob", Age = 30 }
        };

        var sortedPeople = people.OrderBy(p => p.Name);

        foreach (var person in sortedPeople)
        {
            Console.WriteLine($"{person.Name} - {person.Age}");
        }
    }
}
OutputSuccess
Important Notes

OrderBy does not change the original list; it creates a new sorted sequence.

To sort in reverse order, use OrderByDescending instead.

You can chain OrderBy with ThenBy to sort by multiple properties.

Summary

OrderBy helps sort lists by a chosen property or value.

It returns a new sorted sequence without changing the original list.

Use OrderByDescending to sort from largest to smallest.