tags:

views:

793

answers:

3

I expected the following LINQ query to sort according to FirstName but the OrderBy extension method seems to have no effect.

DataClassesDataContext dc = new DataClassesDataContext();

var query = from contact in dc.Contacts
            select contact;

query.OrderBy(c => c.FirstName);

Everything works fine when I include the orderby in the initial query definition but I want to be able to modify it based on conditions later in my code.

Any idea why this isn't working?

+7  A: 

try using

query = query.OrderBy(c => c.FirstName);

or

var sortedQuery = query.OrderBy(c => c.FirstName);

The OrderBy creates a new sequence.

Mike Two
+5  A: 

The problem is that OrderBy is not modifying the existing query. Instead it's creating a new query which orders the values in query. You need to capture this result

var sortedQuery = query.OrderBy(c => c.FirstName);

This is true of virtually every single LINQ operator. The do not actually modify the query in question. Instead they filter or project the result of the query into a new query value and return it from the method.

JaredPar
+4  A: 

In addition to @Mike Two's response, remember that to have multiple sorts you'll need to use ThenBy after the initial OrderBy for it to work, otherwise you'll just replace the first ordering.

var query = from contact in dc.Contacts
        select contact;

query = query.OrderBy(c => c.FirstName); 
query = query.ThenBy(c => c.LastName);

foreach (var contact in query)
{
  ...
}

Actually, my preference would be to chain them all together using extension methods, but obviously this won't work if you need to make them conditional.

var query = dc.Contacts
              .OrderBy( c => c.FirstName )
              .ThenBy( c => c.LastName );

foreach (var contact in query)
{
   ...
}
tvanfosson