Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

c# - LINQ with dynamic group by

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:

  • IsName
  • IsBirthDate
  • IsUniversityName

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?

question from:https://stackoverflow.com/questions/65897919/linq-with-dynamic-group-by

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...