我有一个列表,其类型是字符串,我想按升序排列
listCustomFields = new List<String>() { "FirstName", "MiddleName", "Class" };
You can use LINQ OrderBy
method (it will generate new List<string>
with items sorted):
var ordered = listCustomField.OrderBy(x => x).ToList();
or List<T>.Sort
method (it will sort the list in place):
listCustomField.Sort();
用这个
listCustomFields.sort();
You can use OrderBy
like;
Sorts the elements of a sequence in ascending order.
listCustomFields = listCustomFields.OrderBy(n => n).ToList();
As an alternative, you can use List<T>.Sort
Method also.
List<String> listCustomFields = new List<String>() { "FirstName", "MiddleName", "Class" };
listCustomFields = listCustomFields.OrderBy(n => n).ToList();
foreach (var item in listCustomFields)
{
Console.WriteLine(item);
}
Output will be;
Class
FirstName
MiddleName
Here a DEMO .
You do not need LINQ for that: rather than creating a sorted copy, you can sort your list in place by calling Sort()
method on it:
listCustomFields.Sort();
The order is implicitly ascending. If you need to change that, supply a custom comparer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.