In C#, How Can A List Be Sorted Based On A Property In The Object?

To sort a List by a specific property in the object, you can use the OrderBy or OrderByDescending methods provided by LINQ. Here’s an example:

using System;
using System.Collections.Generic;
using System.Linq;

public class MyClass
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Program
{
    public static void Main(string[] args)
    {
        List<MyClass> myList = new List<MyClass>
        {
            new MyClass { Id = 1, Name = "John" },
            new MyClass { Id = 2, Name = "Alice" },
            new MyClass { Id = 3, Name = "Bob" }
        };

        // Sort by Id in ascending order
        List<MyClass> sortedList = myList.OrderBy(x => x.Id).ToList();

        // Sort by Name in descending order
        List<MyClass> sortedListDescending = myList.OrderByDescending(x => x.Name).ToList();

        // Display the sorted lists
        Console.WriteLine("Sorted list by Id:");
        foreach (MyClass item in sortedList)
        {
            Console.WriteLine($"Id: {item.Id}, Name: {item.Name}");
        }

        Console.WriteLine("\nSorted list by Name (in descending order):");
        foreach (MyClass item in sortedListDescending)
        {
            Console.WriteLine($"Id: {item.Id}, Name: {item.Name}");
        }
    }
}

In the above example, we have a class MyClass with two properties Id and Name. We create a list of MyClass objects and then sort it based on the Id property using OrderBy method. Similarly, we sort it based on the Name property using OrderByDescending method.

Note that we call ToList() after using OrderBy or OrderByDescending to convert the result into a new sorted List<MyClass>. If you don’t need to convert it into a new list, you can omit the ToList() method call.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!