Print Page | Close Window

Dynamic Group By and Count

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2010
Forum Discription: For .NET 4.0
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=2960
Printed Date: 13-May-2026 at 6:18pm


Topic: Dynamic Group By and Count
Posted By: BringerOD
Subject: Dynamic Group By and Count
Date Posted: 15-Sep-2011 at 9:41am
Does anyone know how to get a groupby count from a dynamic query?  I can group by a field, I just can't get it's count without pulling all the records down.   I just want the group field and how many there are.

This works, but only returns the key.
var selector = new AnonymousProjectionSelector().Combine("Key");


This does not.  I was only guessing anyway.
var selector = new AnonymousProjectionSelector().Combine("Key").Combine("Key.Count","Count");


Code

      public void ReadDistinctValuesAndCounts(object sender, QueryGroupsEventArgs e)
      {
         var query = BuildWhereClause(e.CollectionView, e.GroupPath, _baseQuery);
         query = BuildSortClause(e.CollectionView, query);
         var groupByField = e.ChildGroupPropertyName;
         var groupBy = new ProjectionSelector(groupByField);
   
var selector = new AnonymousProjectionSelector().Combine("Key");
         ITypedEntityQuery groupByQuery = query.GroupBy(groupBy).Select(selector);
         
         var result = groupByQuery.Execute();

       }



Replies:
Posted By: BringerOD
Date Posted: 15-Sep-2011 at 3:28pm

I figured out a way to do it using this

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx - http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

It’s a way to do linq queries dynamically.

var result = query.GroupBy(“FieldToGroup”,"it").Select("new(Key as Name, Count() as Total)");

Bryan




Posted By: DenisK
Date Posted: 15-Sep-2011 at 8:16pm
Hi Bryan;

Is this the type of query that you want to do dynamically?

query.GroupBy(g => g.CategoryID).Select(s => new { Name = s.Key, Total = s.Count() });

if so, this is how you would do it,

var groupBySelector = new AnonymousProjectionSelector().Combine("CategoryID");
var selectSelector = new ProjectionSelector("Key", "Name").Combine("Count()", "Total");

var q0 = query.GroupBy(groupBySelector).Select(selectSelector);


Posted By: BringerOD
Date Posted: 15-Sep-2011 at 8:23pm
That looks like it would do it.
 
I did not think to add a select field of "Count()".
 
Thanks



Print Page | Close Window