1

I had a simple Linq query:

var retVal = readModel
    .GroupBy(x => x.Service)
    .Select(
        grp => new GroupView
        {
            GroupName = grp.Key,
            GroupItems = grp.Sum(k => k.NumberOfItems)
        }
    );

retVal was an IQueryable<GroupView>. So far so good, what I'm trying to do is make this query dynamic, so user can use custom grouping strategies.

This is my first attempt:

var retVal = readModel
    .GroupBy("Service", "it")
    .Select("it.key");

And this give me an array of string containing the name of group. This is fine, but the result that I'm trying to achieve is quite far since I have two unanswerd question:

  • How can I translate results to the GroupView model
  • How can I make that sum?
BAD_SEED
  • 4,840
  • 11
  • 53
  • 110
  • What is the type of `GroupName`? a string? would you always group by a property of this type? e.g. string? – Yacoub Massad Aug 18 '16 at 12:17
  • Yes, in this case it is a string, but it could be a Date too, but for now a string it is sufficient. – BAD_SEED Aug 18 '16 at 12:26
  • 3
    Why don't you use your first code but replace `x => x.Service` with a variable of type `Expression>` where `Entity` is your entity type? – Yacoub Massad Aug 18 '16 at 12:29

1 Answers1

0

The thing is DynamicLinq doesn't allow it simply.

You can check this answer if you want to extend DynamicLinq library to return Strongly Typed results.

But if you don't want it here is a simple solution:

//select your grouped results
var retVal = readModel
        .GroupBy("Service", "it")
        .Select("new (it.key as GroupName, Sum(it.NumberOfItems) as GroupItems)");

//Map them
var res = ((IEnumerable<dynamic>)retVal)
          .Select(x => new GroupView 
                 { 
                    GroupName = x.GroupName, 
                    GroupItems = x.GroupItems 
                 });
Community
  • 1
  • 1
teo van kot
  • 12,350
  • 10
  • 38
  • 70