How to sort a List in C# | Code2night.com
Code2night
  • Home
  • Blogs
  • Tutorial
  • Post Blog
  • Members
    • Register
    • Login
  1. Home
  2. Blogpost
01 Jun
2023

How to sort a List in C#

247

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 }.

  • |
  • How to sort a List in C#

Comments

Follow Us On Social Media - Like Us On Facebook

Tags

LinkedinLogin
LinkedinProfile
GetLinkedinProfile
C#
Aspnet
MVC
Linkedin
ITextSharp
Export to Pdf
AspNet Core
AspNet
View to Pdf in Aspnet
Model Validation In ASPNET Core MVC 60
Model Validation
Model Validation In ASPNET Core MVC
Model Validation In ASPNET
Image Compression in AspNet
Compress Image in c#
AspNet MVC
Free Download for New Subscribers!

Subscribe and Click on Verify and Download for download link

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

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading

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 © 2023 by Code2night. All Rights Reserved

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