Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-2024

Using Linq and grouping by variable parameter

    XMLWordPrintableJSON

Details

    • Icon: New Feature New Feature
    • Resolution: Unresolved
    • Icon: Minor - P4 Minor - P4
    • None
    • 2.4.4
    • Linq
    • None
    • net.core 1.1

    Description

      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

      Attachments

        Activity

          People

            Unassigned Unassigned
            lukpep@gmail.com Lucacs Peplinski
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated: