Using Linq and grouping by variable parameter

XMLWordPrintableJSON

    • Type: New Feature
    • Resolution: Won't Do
    • Priority: Minor - P4
    • None
    • Affects Version/s: 2.4.4
    • Component/s: LINQ
    • None
    • Environment:
      net.core 1.1
    • None
    • Hide

      1. What would you like to communicate to the user about this feature?
      2. Would you like the user to see examples of the syntax and/or executable code and its output?
      3. Which versions of the driver/connector does this apply to?

      Show
      1. What would you like to communicate to the user about this feature? 2. Would you like the user to see examples of the syntax and/or executable code and its output? 3. Which versions of the driver/connector does this apply to?
    • None
    • None
    • None
    • None
    • None
    • None

      var result = await Events.AsQueryable()
                  .Where(_ => _.Date >= from.Date && _.Date <= to.Date)
                  .GroupBy(_ => _.SomeProp)
                  .Select(n => new { n.Key, Count = n.Count() })
                  .ToListAsync();
      

      works like charm. But lets say that I want to aggregate by custom field - received in aggregateBy string parameter. So I try:

      var propertyToGroupBy = typeof(DiagnosticEvent).GetProperties()
                    .First(x => x.Name.ToLowerInvariant() == aggregateBy);
      

      And then:

      var result = await Events.AsQueryable()
                  .Where(_ => _.Date >= from.Date && _.Date <= to.Date)
                  .GroupBy(p => propertyToGroupBy.GetValue(p))
                  .Select(n => new { n.Key, Count = n.Count() })
                  .ToListAsync();
      

      Which ends up in exception:
      GetValue of type System.Reflection.PropertyInfo is not supported in the expression tree System.String Type.GetValue(document)

      Any idea how to do it while sticking to LINQ? I know that i can use Fluent API with:

      var group = new BsonDocument { { "_id", $"${aggregateBy}"}, { "Count", new BsonDocument("$sum", 1) } };
      

      But I want to be consistent with LINQ approach.

      Full stack trace: https://pastebin.com/RNzXi1kj

            Assignee:
            Unassigned
            Reporter:
            Lucacs Peplinski
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: