Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I order a List<string>?

Tags:

string

c#

list

People also ask

In what order list of string can be?

A list of strings can be arranged in both ascending and descending order (option c). Sorting is important in programming because it arranges the elements of an array in a specific order.

How do I sort a list in C#?

Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.

How do you sort a list of words in Python?

To sort a list alphabetically in Python, use the sorted() function. The sorted() function sorts the given iterable object in a specific order, which is either ascending or descending. The sorted(iterable, key=None) method takes an optional key that specifies how to sort.

How do you sort a string list without sorting in Python?

You can use Nested for loop with if statement to get the sort a list in Python without sort function. This is not the only way to do it, you can use your own logic to get it done.


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

You can use Sort

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

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.


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.


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