Sort list <> in ascending order

I have a list whose type is a string that I want to sort in ascending order

 listCustomFields = new List<String>() { "FirstName", "MiddleName", "Class" }; 
+6
source share
4 answers

use this

 listCustomFields.sort(); 
+2
source

You can use the LINQ OrderBy method (it will generate a new List<string> with sorted items):

 var ordered = listCustomField.OrderBy(x => x).ToList(); 

or List<T>.Sort (it will sort the list in place):

 listCustomField.Sort(); 
+21
source

You can use OrderBy , for example:

Sorts the elements of a sequence in ascending order.

 listCustomFields = listCustomFields.OrderBy(n => n).ToList(); 

Alternatively, you can also use the List<T>.Sort Method .

 List<String> listCustomFields = new List<String>() { "FirstName", "MiddleName", "Class" }; listCustomFields = listCustomFields.OrderBy(n => n).ToList(); foreach (var item in listCustomFields) { Console.WriteLine(item); } 

The output will be:

 Class FirstName MiddleName 

Here is the demo .

+1
source

You do not need LINQ for this: instead of creating a sorted copy, you can sort your list in place by calling the Sort() method on it:

 listCustomFields.Sort(); 

The order is implicitly increasing. If you need to change this, put a custom comparator.

0
source

Source: https://habr.com/ru/post/952867/


All Articles