tags:

views:

37

answers:

2

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!

A: 

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) };
John Boker
+1  A: 

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 )
                  }; 
tvanfosson
Thanks a lot. It works.
Aaron