Search code examples
c#linqlinq-group

LINQ Group by; How to make it flexible


considering the bit of code at the bottom, this is my problem:

I want to be able to group revenue based on input, e.g.: - Year - Month - Week - Units etc.

Do I need to make a var for each combination (and change the Group by accordingly) or can I make something in which the Group by variables are flexible. Meaning that I can get the LocationRevenue on the level of input for example: week, or month, or year; or year+month together, week+month together or any other combination.

var locationRevenues = revenues
.GroupBy(g => new { Location = g.Location, Month = DateTimeHelper.GetMonth(g.Date)})
.Select(r => new
{
    Location = r.Key,
    RevenueTotal = r.Sum(i => i.RevenueAmount),

})
.ToList();

Solution

  • Each time you add new groupBy select inside groupby clause and press Ctrl + R + M and generate new method. You may pass this as a parameter.

    Do(Func<TSource, TKey>)
    
    var locationRevenues = revenues
                    .GroupBy(Func())
                    .Select(r => new
                    {
                        Location = r.Key,
                        RevenueTotal = r.Sum(i => i.RevenueAmount),
    
                    })
                    .ToList();
    
    
    private static Func<Revenues, object> Func()
    {
        return g => new { Location = g.Location, Month = 9 };
    }