How can I order a List<string>?

C#StringList

C# Problem Overview


I have this List<string>:

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

How can I order it alphabetically and ascending?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

You can use Sort

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

Solution 3 - C#

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.

Solution 4 - C#

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.

Solution 5 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarkzzzView Question on Stackoverflow
Solution 1 - C#daryalView Answer on Stackoverflow
Solution 2 - C#Richard DaltonView Answer on Stackoverflow
Solution 3 - C#phoogView Answer on Stackoverflow
Solution 4 - C#SteView Answer on Stackoverflow
Solution 5 - C#AbdiView Answer on Stackoverflow