1

I have the following query which does not work

var municipalities = session.Query<Repositorio_Resultado>()
                .Where(x => ...)
                .GroupBy(GetExpression(argument))
                .Select(x => new SelGeo_DTO()
                 { 
                     COORD_LAT = x.Average(y => y.CoordYLat.Value),
                     COORD_LON = x.Average(y => y.CoordXLon.Value)
                })
                .ToList();

where GetExpression is this

private Expression<Func<Repositorio_Resultado, object>> GetExpression(string level2GroupBy)
    {
        ParameterExpression pe = Expression.Parameter(typeof(Repositorio_Resultado), "x");

        Type anonymousType = new { Key1 = "", Key2 = "" }.GetType();
        NewExpression ne = Expression.New(anonymousType);
        MemberInitExpression mie = Expression.MemberInit(ne, new MemberBinding[]
        {
            Expression.Bind(anonymousType.GetMember("Key1")[0], Expression.Constant(level2GroupBy)),
            Expression.Bind(anonymousType.GetMember("Key2")[0], Expression.Constant(string.Format("ID_{0}", level2GroupBy)))
        });

        return Expression.Lambda<Func<Repositorio_Resultado, object>>(mie, pe);
    }

what I want to do is implement

.GroupBy(x => new { x.A, x.B })

and then in the Select that follows I want to use x.Key.Key1, x.Key.Key2. Currently the error I get is

Type '<>f__AnonymousType2`2[System.String,System.String]' does not have a default constructor

on the NewExpression ne = Expression.New(anonymousType); line. I am not sure on the return type of the GetExpression method too, it's probably wrong.

  • try see about [memberinitexpression](https://msdn.microsoft.com/en-us/library/system.linq.expressions.memberinitexpression(v=vs.110).aspx) – Grundy Jun 15 '15 at 15:54
  • possible duplicate of [How to create LINQ Expression Tree to select an anonymous type](http://stackoverflow.com/questions/606104/how-to-create-linq-expression-tree-to-select-an-anonymous-type) – Grundy Jun 15 '15 at 15:57
  • I would like to use the dynamic linq library, using strings. Do you know how to write that select clause in that way? – Konstantinos Papakonstantinou Jun 16 '15 at 09:43
  • if you use DynamicLinq so it should be something like this `.GroupBy("new(it.A, it.B)")` – Grundy Jun 16 '15 at 10:14
  • when you say _dynamic linq library_ you mean this https://dynamiclinq.codeplex.com/ or something else? – Grundy Jun 16 '15 at 10:58
  • if so, you can use `var tt = t.GroupBy("new (it.num, it.num2)", "it");` – Grundy Jun 16 '15 at 11:07
  • I abandoned dynamic linq and now am back in trying to solve my problem with expression trees, can you help Grundy? – Konstantinos Papakonstantinou Jun 19 '15 at 18:54
  • if you want epression trees, see link above - you can see complex sample for creating and using anonymous type with expresion tree – Grundy Jun 20 '15 at 09:12

0 Answers0