如何订购List <string>?


Answers:


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

@Servy使用OrderBy的原因之一是ListaServizi没有Sort方法,因为它被声明为IList<string>。该代码实际上可以按书面形式工作,与使用接受更多投票的答案不同ListaServizi.Sort()。我并不是说这是我选择的解决方案,但这实际上是我发布答案时唯一的正确答案。
phoog 2012年

如果不是您选择的解决方案,那为什么要提出答案呢?提出答案。如果那意味着将类型从IList更改为List以便可以调用.Sort它,那为什么不这样做。
Servy

1
@Servy他在不更改问题规范的情况下解决了该问题。到目前为止,这是首选方式。此外,问题陈述使用接口而非实现模式,这非常重要。提议对列表类型进行更改是正确的,但应在正确答案之后作为替代答案,因为它需要更改问题。
Aurelien Ribon 2014年

1
@AurélienRibon关于问题声明的任何内容都说不能更改变量的类型。要求非常明确地要排序List。与这个答案相关的成本是不平凡的,也是不必要的。从字面上看,它什么也得不到。它增加了代码的复杂性,简洁性降低,效率降低,在这里实际上没有缺点。
2014年


12

其他答案是正确的建议Sort,但它们似乎错过了将存储位置键入为的事实IList<stringSort不是界面的一部分。

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

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

也许更惯用:

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

如果您知道ListaServizi有时会使用的不同实现IList<string>,请发表评论,然后添加一两个建议进行排序。


5
ListaServizi.Sort();

将为您做到这一点。列出字符串很简单。如果对对象进行排序,则需要变得更聪明。


3
ListaServiziIList<string>; 接口没有Sort方法。您至少在这里需要演员。
phoog 2012年

3
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));
}

输出:Abdi 3 Alex 2 Bob 4

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.