[CSHARP-2024] Using Linq and grouping by variable parameter Created: 28/Jul/17  Updated: 31/Mar/22

Status: Backlog
Project: C# Driver
Component/s: Linq
Affects Version/s: 2.4.4
Fix Version/s: None

Type: New Feature Priority: Minor - P4
Reporter: Lucacs Peplinski Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

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



 Comments   
Comment by Robert Stam [ 07/Sep/17 ]

As you have already verified this is not currently supported and we don't have any current plans to support specifying which property to group by using a PropertyInfo.

I'll leave this ticket open for now as a possible future enhancement.

Generated at Wed Feb 07 21:41:24 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.