C# 按升序排列 List<>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18545988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Arrange List<> in ascending order
提问by Murtaza Munshi
I have a list whose type is string which i want to arrange in ascending order
我有一个类型为字符串的列表,我想按升序排列
listCustomFields = new List<String>() { "FirstName", "MiddleName", "Class" };
采纳答案by Amit Bisht
use this
用这个
listCustomFields.sort();
回答by MarcinJuraszek
You can use LINQ OrderBy
method (it will generate new List<string>
with items sorted):
您可以使用 LINQOrderBy
方法(它将生成新的List<string>
排序项目):
var ordered = listCustomField.OrderBy(x => x).ToList();
or List<T>.Sort
method (it will sort the list in place):
或List<T>.Sort
方法(它将对列表进行排序):
listCustomField.Sort();
回答by Soner G?nül
You can use OrderBy
like;
你可以使用OrderBy
喜欢;
Sorts the elements of a sequence in ascending order.
按升序对序列的元素进行排序。
listCustomFields = listCustomFields.OrderBy(n => n).ToList();
As an alternative, you can use List<T>.Sort
Methodalso.
作为替代方案,您也可以使用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);
}
Output will be;
输出将是;
Class
FirstName
MiddleName
Here a DEMO.
这里有一个演示。
回答by dasblinkenlight
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:
为此,您不需要 LINQ:您可以通过调用Sort()
方法对列表进行排序,而不是创建已排序的副本:
listCustomFields.Sort();
The order is implicitly ascending. If you need to change that, supply a custom comparer.
顺序是隐式升序。如果您需要更改它,请提供自定义比较器。