How can I order a List<string>?

I have this List<string>:

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

How can I order it alphabetically and ascending?


Solution 1:

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

Solution 2:

You can use Sort

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

Solution 3:

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.