Question:
How to Group large number of data based on CreatedDate(DateTime)?

Solution:

For server-side functionality, Expression\Func<,>> is required. Although I'm not sure how EF will handle DateTime as a grouping key, I added DateGroupingKey.

class DateGroupingKey

{

    public int Year [ get; set; ]

    public int Month [ get; set; ]

    public int Day [ get; set; ]

}



var baseQuery = _uow.BusinessSalesRepo

    .GetAll(sale => sale.BusinessId == BusinessId && sale.CreatedByBusinessCrew.BranchId == BranchId);



Expression<Func<DateTime, DateGroupingKey>> groupKeySelector;


switch (filterBy)

{

    case (int)BusinessSalesFilteredBy.Month:

        groupKeySelector = sale => new DateGroupingKey { 

            Year = sale.CreateDate.Value.Year, Month = sale.CreateDate.Value.Month 

        }

        break;

    case (int)BusinessSalesFilteredBy.Year:

        groupKeySelector = sale => new DateGroupingKey { 

            Year = sale.CreateDate.Value.Year 

        }

       break;

    default:

        // Default to daily grouping

        groupKeySelector = sale => new DateGroupingKey { 

            Year = sale.CreateDate.Value.Year, Month = sale.CreateDate.Value.Month, Day = sale.CreateDate.Value.Day 

        }


      break;

}


ar summaryQuery = baseQuery

    .GroupBy(groupKeySelector)

    .Select(grouped => new

    {

        SalesOn = grouped.Key,

        SalesCount = grouped.Count(),

        ClientCount = grouped.Select(x => x.ClientProfileId).Distinct().Count(),

        SumPurchases = grouped.Sum(x => x.PurchasedAmount ?? 0)

    });

var pagedSummary = await summaryQuery.ToListAsync();


Suggested blogs:

>>Laravel Query Solved: Laravel withOnly not restricting the query

>>Laravel installation problem: Fix failed to download laravel/laravel from dist- Laravel (v10.2.6)

>>How to fix when Postgres connection refused while running laravel tests on gitlab CI?

>>Changing main page as Identity's Login page in ASP.NET Core 7

>>How can I get the original type of a Mock after the Mock has been cast to an object

>>Fix Cookie doesn't work error in .NET 6 Web API

>>Build an Electron application from scratch

>>Build Progressive Web Apps with Angular


Ritu Singh

Ritu Singh

Submit
0 Answers