I want to count user registrations by month, currently the code I have works, but I want some feedback or some ideas on how to do it in a better way because I think mine looks a bit messy.
Using a Unit of Work Implementation with the Repository pattern:
var repository = _unitOfWork.GetBaseRepository<Customer>();
Use Lambda expression to get the CreatedOn
property from the Customers object
var customerList = await repository.GetListAsync(cancellationToken: cancellationToken);
var customers = customerList.Where(q => q.DateCreated.HasValue && q.DateCreated.Value.Date <= DateTimeOffset.UtcNow);
Initialize a new Dictionary so I can use Key-Values to store the count of users on each month.
var months = new Dictionary<string, int>
{
{"January", 0}, {"February", 0},
{"March", 0}, {"April", 0},
{"May", 0}, {"June", 0},
{"July", 0}, {"August", 0},
{"September", 0}, {"October", 0},
{"November", 0}, {"December", 0}
};
iterate over the customers collection and use a switch statement to match the DateTime.Month (1-12), increment the value of key by 1.
foreach (var customer in customers)
if (customer.CreatedOn != null)
switch (customer.CreatedOn.Value.Month)
{
case 1:
months["January"] = +1;
break;
case 2:
months["February"] = +1;
break;
case 3:
months["March"] = +1;
break;
case 4:
months["April"] = +1;
break;
case 5:
months["May"] = +1;
break;
case 6:
months["June"] = +1;
break;
case 7:
months["July"] = +1;
break;
case 8:
months["August"] = +1;
break;
case 9:
months["September"] = +1;
break;
case 10:
months["October"] = +1;
break;
case 11:
months["November"] = +1;
break;
case 12:
months["December"] = +1;
break;
}
iterate with foreach over the months collection using destructuring and LINQ to transform the dictionary into a JSON response
var prettifiedList = new List<string>();
foreach (var (key, value) in months) prettifiedList.Add(@$"{key}: {value}");
return await Result<List<string>>.SuccessAsync(prettifiedList);
post was originally on stackoverflow but closed due to 'opinion-based': https://stackoverflow.com/posts/70365375