Sorting a List with OrderBy
Why won't the code belo开发者_如何学Cw sort my list?
List<string> lst = new List<string>() { "bac", "abc", "cab" };
lst.OrderBy(p => p.Substring(0));
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.
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);
}
精彩评论