How to sort a List in C# | Code2night.com
Code2night
  • Home
  • Blogs
  • Guest Posts
  • Tutorial
  • Post Blog
  • Register
  • Login
  1. Home
  2. Blogpost

How to sort a List in C#

Date- Jun 01,2023

3744

In C#, you can use the Sort method to sort a List in ascending order. Here's an example of how you can sort a list of integers:

List<int> numbers = new List<int> { 4, 2, 7, 1, 9 };
numbers.Sort();

After executing the Sort method, the numbers list will be sorted in ascending order: { 1, 2, 4, 7, 9 }.

If you want to sort a list of objects based on a specific property, you can use the Sort method with a custom comparison. Here's an example where we sort a list of Person objects based on their Name property:

class Person
{
    public string Name { get; set; }
    // other properties
}

List<Person> people = new List<Person>
{
    new Person { Name = "Alice" },
    new Person { Name = "Charlie" },
    new Person { Name = "Bob" }
};

people.Sort((p1, p2) => p1.Name.CompareTo(p2.Name));

After executing the Sort method with the custom comparison, the people list will be sorted alphabetically by name: { "Alice", "Bob", "Charlie" }.

Alternatively, if you want to sort a list in descending order, you can use the Sort method with a custom comparison and reverse the result using the Reverse method:

List<int> numbers = new List<int> { 4, 2, 7, 1, 9 };
numbers.Sort((x, y) => y.CompareTo(x));
numbers.Reverse();
After executing these two methods, the numbers list will be sorted in descending order: { 9, 7, 4, 2, 1 }.

Comments

Tags

Swagger UI
Swashbuckle
SwashbuckleAspNetCore
Rest API
Postman
Api Testing
ITextSharp
Export to Pdf
AspNet Core
AspNet
C#
View to Pdf in Aspnet
Scheduler
Fibonacci series in Java
Display Fibonacci Series
First C# Program
What is C?
C
C Programming
CodeLobster
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp Join Us On Facebook

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Panipat
  • info@Code2night.com

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2026 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Terms & Conditions
  • Refund Policy
  • About Us
  • Privacy Policy
  • Json Beautifier
  • Guest Posts