ROL
ROL

Reputation: 201

Sorting a List with OrderBy

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

Answers (3)

Bastardo
Bastardo

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

Stephen Chung
Stephen Chung

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

scatman
scatman

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

Related Questions