Reputation: 201
Why won't the code below sort my list?
List<string> lst = new List<string>() { "bac", "abc", "cab" };
lst.OrderBy(p => p.Substring(0));
Upvotes: 19
Views: 69336
Reputation: 4152
string[] words = { "bac", "abc", "cab" };
var sortedWords = from w in words
orderby w
select w;
Console.WriteLine("The sorted list of words:");
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
Upvotes: 1
Reputation: 14605
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.
Upvotes: 23
Reputation: 14555
since OrderBy returns IOrderedEnumerable you should do:
lst = lst.OrderBy(p => p.Substring(0)).ToList();
you can also do the following:
lst.Sort();
Upvotes: 28