Aaron
Aaron

Reputation: 155

how to order a group result with Linq?

How can I order the results from "group ... by... into..." statement in linq? For instance:

var queryResult = from records in container.tableWhatever
                  where records.Time >= DateTime.Today
                  group records by tableWhatever.tableHeader.UserId into userRecords
                  select new { UserID = userRecords.Key, Records = userRecords };

The query returns records in table "contain.tableWhatever" grouped by "UserId". I want the returned results within each group ordered by time decending. How can I do that?

More specific, assume the above query return only one group like the following:

{UserID = 1, Records= {name1 5/3/2010_7:10pm;
                       name2 5/3/2010_8:10pm;
                       name3 5/3/2010_9:10pm} }

After insert the orderby statement in the above query, the returned results should be like this:

{UserID = 1, Records= {name3 5/3/2010_9:10pm;
                       name2 5/3/2010_8:10pm;
                       name1 5/3/2010_7:10pm} }

Thanks for help!

Upvotes: 1

Views: 895

Answers (2)

tvanfosson
tvanfosson

Reputation: 532435

Simply use the OrderByDescending extension to order the records in the anonymous type.

var queryResult = from records in container.tableWhatever 
                  where records.Time >= DateTime.Today 
                  group records by tableWhatever.tableHeader.UserId into userRecords 
                  select new
                  {
                       UserID = userRecords.Key,
                       Records = userRecords.OrderByDescending( u => u.Time )
                  }; 

Upvotes: 2

John Boker
John Boker

Reputation: 83699

could you do:

var queryResult = from records in container.tableWhatever
              where records.Time >= DateTime.Today
              group records by tableWhatever.tableHeader.UserId into userRecords
              select new { UserID = userRecords.Key, Records = userRecords.OrderByDescending(r=>r.Time) };

Upvotes: 0

Related Questions