Reputation: 87
I have model:
public class Student
{
public string Name{ get; set; }
public DateTime BirthDate{ get; set; }
public string UniversityName{ get; set; }
public decimal Balance{ get; set; }
}
I have three bool
variables:
And based on them, I need to create GroupBy
. If IsBirthDate=true
then
DbContext.Students.GroupBy(x => new { x.BirthDate }).Select(s => new
{
s.Key.BirthDate,
Balance = s.Sum(x => x.Balance).ToString(),
});
If IsBirthdate=true, IsUniversityName=true
then
DbContext.Students.GroupBy(x => new { x.BirthDate, x.UniversityName }).Select(s => new
{
s.Key.BirthDate,
s.Key.UniversityName,
Balance = s.Sum(x => x.Balance).ToString(),
});
And other options with bool parameters.
How to generate the query dynamically with .GroupBy and .Select
?
Upvotes: 1
Views: 126
Reputation: 8743
Maybe this helps you: Create a class that represents the key for your GroupBy
:
public class StudentGroupingKey
{
public string Name { get; set; }
public DateTime? BirthDate{ get; set; }
public string UniversityName { get; set; }
}
If IsName
is true, the Name
property of the grouping key will be the value, otherwise it should have always the same value (e.g. null). In your Select
method, you have to have always every property, but they will be null if the corresponding properties will be false. If it is necessary for you that these properties do not exist, you can't work with anoymous types. Maybe dynamic
might be an option in that case.
DbContext.Students.GroupBy(x => new StudentGroupingKey
{
Name = IsName ? x.Name : null,
BirthDate = IsBirthDate ? x.Birthdate : null,
UniversityName = IsUniversityName ? x.UniversityName : null
}).Select(s => new
{
s.Key.BirthDate,
s.Key.Name,
s.Key.UniversityName,
Balance = s.Sum(x => x.Balance).ToString()
});
Upvotes: 3