سؤال

I'm using linqpad, and when I group it does an awesome job of displaying tables for each key that I'm grouping by. But I can't sort the tables that are presented.

Here is what I have:

tblAgentActivities
.Where (aa => aa.StartDate >= DateTime.Today)
.OrderBy (aa => aa.AgentActivityID)
.GroupBy (aa => aa.tblUser.FullName)
.OrderBy (aa => aa.Key)

I want the groups to be sorted by key (that's working), then I want the grouped tables to be sorted by AgentActivityID (which isn't working)

هل كانت مفيدة؟

المحلول

If your query was a LINQ-to-Objects query, it would work correctly as-is, so I take it that you're querying a database via LINQ-to-SQL or Entity Framework.

In which case the solution is to insert .AsEnumerable() into the query, so that the grouping and subsequent sorting happens on the client side:

tblAgentActivities
  .Where (aa => aa.StartDate >= DateTime.Today)
  .OrderBy (aa => aa.AgentActivityID)
  .AsEnumerable()
  .GroupBy (aa => aa.tblUser.FullName)
  .OrderBy (aa => aa.Key)

Given that you're fetching all of the grouped data to the client, there's no performance penalty is grouping on the client rather than the server; in fact, you'll improve scalability by relieving the database server from some unnecessary burden.

نصائح أخرى

how about this :

tblAgentActivities
            .Where (aa => aa.StartDate >= DateTime.Today)
            .GroupBy (aa => aa.tblUser.FullName)
            .Select(aa => new {

                FullName = aa.Key,
                List = aa.OrderBy(u => u.AgentActivityID).AsEnumerable()
            })
            .OrderBy (aa => aa.FullName)
            .ToList();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top