3

I'm trying to create nested group with dynamic query.

Following are my collection of data

var invoices = new List < Purchase > () {
    new Purchase() {
        Id = 1, Customer = "a", Date = DateTime.Parse("1/1/2009")
    }, new Purchase() {
        Id = 2, Customer = "a", Date = DateTime.Parse("1/2/2009")
    }, new Purchase() {
        Id = 3, Customer = "a", Date = DateTime.Parse("1/2/2009")
    }, new Purchase() {
        Id = 4, Customer = "b", Date = DateTime.Parse("1/1/2009")
    }, new Purchase() {
        Id = 5, Customer = "b", Date = DateTime.Parse("1/1/2009")
    }, new Purchase() {
        Id = 6, Customer = "b", Date = DateTime.Parse("1/2/2009")
    }
 };

This linq query is returning the desired result.

  var tree = invoices.GroupBy(x => x.Date).Select(x => new
        {
            Key = x.Key,
            Items = x.GroupBy(y => y.Customer).Select(y => new
            {
                Key = y.Key,
                Items = y
            })
        }).ToList();

Below is the output of the above linq query

Output of linq query result

But I just need to group different columns in different order.

So that I try to create dynamic linq query. But my code block result not same as my previous linq query.

var groupedInvoiceItems = invoices.AsQueryable().GroupBy("new (Date, Customer)", "it");
ekad
  • 14,436
  • 26
  • 44
  • 46
deadpool
  • 31
  • 2
  • What's the result of your dynamic query? – ZwoRmi Oct 12 '15 at 09:40
  • What do you mean by **dynamic query**? Is it something related to [System.Linq.Dynamic](https://dynamiclinq.codeplex.com/)? – Ivan Stoev Oct 12 '15 at 10:49
  • i mean Dynamic LINQ Query . check following link http://www.c-sharpcorner.com/UploadFile/deveshomar/dynamic-linq-library-in-C-Sharp/ – deadpool Oct 12 '15 at 14:27
  • Which is the same as in my link. You need to clearly state such things, as you may see these are unofficial sources, so no one is supposed to know what do you mean by such terms. What about the concrete issue, I don't think they support what you are asking for, but might be wrong of course. Good luck. – Ivan Stoev Oct 12 '15 at 16:51

1 Answers1

0

You could do this with Generics. Just Pass in your Lambda to a generic method.

Something like:

private IEnumerable<PurchaseGrp> BuildList<TSource>(IQueryable<TSource> allRecords,
            Func<TSource, string> selector)
{
   var result = allRecords.GroupBy(x = > x.selector(x));
   return result;
}

The return type could be a new Grouped type PurchaseGrp or the same as your source (Purchase).

Jenish Rabadiya
  • 6,708
  • 6
  • 33
  • 62
Paul
  • 1,483
  • 14
  • 32
  • You shouldn't be accepting an `IQueryable` if you're just going to treat it like an `IEnumerable`. This won't allow the operation to happen in the database. – Servy Oct 19 '15 at 14:31