1

Suppose I have a class

public class Item
{ 
    public int Field1{get;set;}
    ……
    public int FieldN{get;set;}
}

And I want to use group by like this;

Collection.GroupBy(selector“Field1,…,FieldK”)
          .Select(x=> new Item
              {
                  Field1 = x.Key.Field1,
                   …
                  FieldK= x.Key.FieldK,
                  FiledK+1= x.Sum(x.FieldK+1),
                  ….
                  FiledN= x.Sum(x.FieldN)
              };

How can I do this using Expresions Tree

Bradley Uffner
  • 16,641
  • 3
  • 39
  • 76
mahul17
  • 21
  • 2
  • are you sure what you want is the expression tree? maybe you are looking for the **Query Syntax** of the linq statements you wrote using **Method Syntax**. Is this the case? – Shahryar Saljoughi Mar 18 '19 at 19:02
  • 1
    How big is `N`? – D Stanley Mar 18 '19 at 19:03
  • 1
    I think he wants to dynamically generate the fields used for grouping, which would require expression trees to programatically create the expression passed in the first parameter to `GroupBy`. Some clarity from OP would be helpful in knowing for sure though. – Bradley Uffner Mar 18 '19 at 19:04

1 Answers1

0

Welcome to stackoverflow mahul! What you want can be achieved like this:

var a = from item in collection
        group item by new {item.Field1, ... , item.Fieldk} into newGroup
        select new {
            Field1 = newGroup.Key.Field1
            Field2 = newGroup.Key.Field1
            ...
            FieldK+1 = newGroup.Sum(x => x.FieldK+1),
            ...
            FieldN = newGroiup.Sum(x => x.FieldN)
         }

make sure to read the documentation too. There are good examples there .

Shahryar Saljoughi
  • 2,599
  • 22
  • 41
  • `FieldK+1 = newGroup.Sum(x => x.FieldK+1),` will not work. – D Stanley Mar 18 '19 at 19:03
  • @DStanley This is just a pseudocode and should be replaced with the real code . That is a notation to represent the (K+1)th field. – Shahryar Saljoughi Mar 18 '19 at 19:23
  • 1
    I understand that - how do you propose to implement that when K is not known? – D Stanley Mar 18 '19 at 19:26
  • @DStanley aha, I see. You are right in case K is not specified in compile time. But the op has not mentioned that he is trying to generate query dynamically. I'll remove this answer if the OP's provides us with more clarification. – Shahryar Saljoughi Mar 18 '19 at 19:34
  • by K+1 i meant Next Field. my code is just an imaginary. Anyway, I solve my problem for the Grouping using Expression Tree, Now I am working on GroupJoin. – mahul17 Mar 19 '19 at 17:32