C# 如何订购 List<string>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10211470/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:54:05  来源:igfitidea点击:

How can I order a List<string>?

c#stringlist

提问by markzzz

I have this List<string>:

我有这个List<string>

IList<string> ListaServizi = new List<string>();

How can I order it alphabetically and ascending?

如何按字母顺序和升序排序?

采纳答案by daryal

ListaServizi = ListaServizi.OrderBy(q => q).ToList();

回答by Richard Dalton

You can use Sort

您可以使用排序

List<string> ListaServizi = new List<string>() { };
ListaServizi.Sort();

回答by Ste

ListaServizi.Sort();

Will do that for you. It's straightforward enough with a list of strings. You need to be a little cleverer if sorting objects.

会为你做的。使用字符串列表就足够简单了。如果排序对象,您需要更聪明一点。

回答by phoog

Other answers are correct to suggest Sort, but they seem to have missed the fact that the storage location is typed as IList<string. Sortis not part of the interface.

建议的其他答案是正确的Sort,但他们似乎忽略了存储位置键入为IList<string. Sort不是界面的一部分。

If you know that ListaServiziwill always contain a List<string>, you can either change its declared type, or use a cast. If you're not sure, you can test the type:

如果您知道它ListaServizi始终包含 a List<string>,则可以更改其声明的类型,或使用强制转换。如果您不确定,可以测试类型:

if (typeof(List<string>).IsAssignableFrom(ListaServizi.GetType()))
    ((List<string>)ListaServizi).Sort();
else
{
    //... some other solution; there are a few to choose from.
}

Perhaps more idiomatic:

也许更地道:

List<string> typeCheck = ListaServizi as List<string>;
if (typeCheck != null)
    typeCheck.Sort();
else
{
    //... some other solution; there are a few to choose from.
}

If you know that ListaServiziwill sometimes hold a different implementation of IList<string>, leave a comment, and I'll add a suggestion or two for sorting it.

如果您知道这ListaServizi有时会包含 的不同实现IList<string>,请发表评论,我会添加一两个建议以对其进行排序。

回答by Abdi

List<string> myCollection = new List<string>()
{
    "Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};

myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
    Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}

output: Abdi 3 Alex 2 Bob 4

输出:阿布迪 3 亚历克斯 2 鲍勃 4