How can I order a List?

后端 未结 5 1590
孤城傲影
孤城傲影 2020-12-07 21:40

I have this List:

IList ListaServizi = new List();

How can I order it alphabetically

相关标签:
5条回答
  • 2020-12-07 22:05
    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

    0 讨论(0)
  • 2020-12-07 22:07
    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.

    0 讨论(0)
  • 2020-12-07 22:11

    You can use Sort

    List<string> ListaServizi = new List<string>() { };
    ListaServizi.Sort();
    
    0 讨论(0)
  • 2020-12-07 22:19

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

    If you know that ListaServizi will 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:

    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 ListaServizi will sometimes hold a different implementation of IList<string>, leave a comment, and I'll add a suggestion or two for sorting it.

    0 讨论(0)
  • 2020-12-07 22:23
    ListaServizi = ListaServizi.OrderBy(q => q).ToList();
    
    0 讨论(0)
提交回复
热议问题