There is such code:

var query = from data in db.GetTable<TableClass>() group data by new { data.Organisation, data.City } into result select new { Organisation = result.Key.Organisation, City = result.Key.City, Quantity = result.Sum(i => i.Quantity), Summa = result.Sum(i => i.Summa) }; 

How can you make it so that you can dynamically change the fields by which they are grouped. For example:

 var query = from data in db.GetTable<TableClass>() group data by new { data.Manager, data.Organisation, data.Date } into result select new { Manager = result.Key.Manager; Organisation = result.Key.Organisation, Date = result.Key.Date, Quantity = result.Sum(i => i.Quantity), Summa = result.Sum(i => i.Summa) }; 

    2 answers 2

    For example:

     group data by new { data.Manager, Organisation = condition ? data.Organisation : "" } into result 

    Depending on the condition grouping will be on 1 field or 2.

    • In fact, this is not a good idea - the optimizer will not be able to build the right plan for such queries. - Pavel Mayorov

    Solved a problem with the help of the library System.Linq.Dynamic

    This is what happened:

      string groupingQuery = "new(City, Country)"; string selectQuery = "Key.City, Key.Country"; var query = db.GetTable<TableClass>().GroupBy(groupingQuery, "new(Quantity,Summa)") .Select($"new({selectQuery}, Sum(Quantity) as Quantity, Sum(Summa) as Summa)"); 

    We form the necessary lines, and further we insert them into the request.