Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a List<int>

Tags:

c#

list

linq

Using C# what is the best way to sort a List numerically? my list has items 5,7,3 and I would like them sorted 3,5,7. I know some longer ways, but I would imagine linq has a quicker way?

sorry this was end of day, my mind is else where it worked, didn't see it change the first time:(

like image 847
Spooks Avatar asked Sep 17 '10 20:09

Spooks


2 Answers

There's no need for LINQ here, just call Sort:

list.Sort(); 

Example code:

List<int> list = new List<int> { 5, 7, 3 }; list.Sort(); foreach (int x in list) {     Console.WriteLine(x); } 

Result:

3 5 7 
like image 157
Mark Byers Avatar answered Sep 23 '22 03:09

Mark Byers


Keeping it simple is the key.

Try Below.

var values = new int[5,7,3]; values = values.OrderBy(p => p).ToList(); 
like image 31
Khizer Jalal Avatar answered Sep 20 '22 03:09

Khizer Jalal