Why won't the code below sort my list?
List<string> lst = new List<string>() { "bac", "abc", "cab" };
lst.OrderBy(p => p.Substring(0));
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.
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.
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.
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.
since OrderBy returns IOrderedEnumerable you should do:
lst = lst.OrderBy(p => p.Substring(0)).ToList();
you can also do the following:
lst.Sort();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With