3

I have the following enumeration Extension method:

public static Expression<Func<Table, object>> GetGroupByClause(this OntDubbelingsEigenschappen o)
{
    switch (o)
    {
        case OntDubbelingsEigenschappen.Voornaam:
            return w => w.TableField1;
        case OntDubbelingsEigenschappen.Achternaam:
            return w => w.TableField2;
        case OntDubbelingsEigenschappen.Emailadres:
            return w => w.TableField3;
        case OntDubbelingsEigenschappen.GeboorteDatum:
            return w => w.TableField4;
        default:
            return null;
    }
}

Now I want to use this extension to create the following query:

List<Expression<Func<Table, object>>> delList = new List<Expression<Func<Table, object>>>();
ontdubbelEigenschapIds.ForEach(f => delList.Add(f.GetGroupByClause()));            
var users = Db.Table.GroupBy(x => new { delList })
            .SelectMany(s => s).ToList().Select(s => 
            new Model(s, isOverTakeActive)).ToList();

This does not work, because I am passing a non-primitive type along in the query. How can I do this in a correct way?

dtlvd
  • 457
  • 1
  • 8
  • 21
Kai
  • 732
  • 1
  • 7
  • 23
  • `GroupBy` (both the `Queryable` and `Enumerable` version) has a `TKey` generic argument. You seem to want to decide upon the type of this generic argument at run time but that is not possible (unless you generate code). – Martin Liversage Apr 06 '18 at 10:14
  • Not a full answer but I've done something similar with multiple `OrderBy`s. Basically what you would need is a combination of Expressions and Reflection to get the proper overload based on the field/property. Maybe this helps: [OrderBy based on list of fields and Asc / Desc rules](https://stackoverflow.com/a/37631507/3214843) – Manfred Radlwimmer Apr 06 '18 at 10:22
  • if this is to be used to generate dynamicaly grouped queries for EF ... have a look at dynamic linq ... https://github.com/StefH/System.Linq.Dynamic.Core – DarkSquirrel42 Apr 06 '18 at 10:25

1 Answers1

0

there is a nice solution to this by Mitsu Furuta ...

https://blogs.msdn.microsoft.com/mitsu/2007/12/21/playing-with-linq-grouping-groupbymany/

it does not produce a flattened out grouping though...

if you want to flatten the resulting tree, the groups you want to look at are the leaves of the tree ... screams for a little recursion with yield return

DarkSquirrel42
  • 10,167
  • 3
  • 20
  • 31
  • 1
    While this idea of using multiple groupings might be a way to solve the problem this only works on the "client side". While not obvious from the question my guess is that the grouping should be performed on the "server side" using `IQueryable` instead of `IEnumerable`. This is based on the occurrence of `ToList` after `SelectMany` but before `Select`. I might be wrong of course. – Martin Liversage Apr 06 '18 at 10:19
  • Exactly. The number of properties is also dynamic, so I do not want to literally paste in the propertynames – Kai Apr 06 '18 at 10:24