Dynamic Linq Select to a complex object

c# dynamic-linq linq

Question

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?
1
1
8/18/2016 12:14:49 PM

Popular Answer

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 
                 });
0
5/23/2017 10:28:38 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow