How can I order a List?

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

I have this List:

IList ListaServizi = new List();

How can I order it alphabetically

5条回答
  •  不思量自难忘°
    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. Sort is not part of the interface.

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

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

    Perhaps more idiomatic:

    List typeCheck = ListaServizi as List;
    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, leave a comment, and I'll add a suggestion or two for sorting it.

提交回复
热议问题