Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a List with OrderBy

Tags:

c#

linq

Why won't the code below sort my list?

List<string> lst = new List<string>() { "bac", "abc", "cab" };
lst.OrderBy(p => p.Substring(0));
like image 392
ROL Avatar asked Mar 14 '11 07:03

ROL


People also ask

Does OrderBy sort in place?

orderBy() Unlike sort() , the orderBy() function guarantees a total order in the output. This happens because the data will be collected into a single executor in order to be sorted.

How do you 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 I sort in LINQ?

LINQ includes five sorting operators: OrderBy, OrderByDescending, ThenBy, ThenByDescending and Reverse. LINQ query syntax does not support OrderByDescending, ThenBy, ThenByDescending and Reverse. It only supports 'Order By' clause with 'ascending' and 'descending' sorting direction.

How does OrderBy and ThenBy work?

The ThenBy and ThenByDescending extension methods are used for sorting on multiple fields. The OrderBy() method sorts the collection in ascending order based on specified field. Use ThenBy() method after OrderBy to sort the collection on another field in ascending order.


2 Answers

since OrderBy returns IOrderedEnumerable you should do:

lst = lst.OrderBy(p => p.Substring(0)).ToList();

you can also do the following:

lst.Sort();
like image 88
scatman Avatar answered Oct 08 '22 17:10

scatman


You are confusing LINQ operations with a method that changes the variable it is applied to (i.e. an instance method of the object).

LINQ operations (i.e. the .OrderBy) returns a query. It does not perform the operation on your object (i.e. lst).

You need to assign the result of that query back to your variable:

lst = lst.OrderBy(p => p).ToList();

in LINQ lingo.

like image 25
Stephen Chung Avatar answered Oct 08 '22 17:10

Stephen Chung