You can dynamically add a calculation with one DB call, as shown in the snap code below.
Instead of making three separate database calls to calculate sales for each year, we can optimize by fetching all the required data in a single DB call.
int numberOfPastYears = 5; // Specify the number of past years you want to consider
int currentYear = DateTime.Now.Year;
DateTime startDate = new DateTime(currentYear - numberOfPastYears + 1, 1, 1);
DateTime endDate = new DateTime(currentYear + 1, 1, 1); // Next year's start date
var salesByYear = Db.OrderRel
.Where(r => r.Company == Session.CompanyID
&& r.PartNum == ttJobHead_xRow.PartNum
&& r.ReqDate >= startDate
&& r.ReqDate < endDate)
.GroupBy(r => r.ReqDate.Year)
.Select(group => new
{
Year = group.Key,
Sales = group.Sum(r => r.OurJobShippedQty + r.OurStockShippedQty)
})
.ToList();
// Initialize dictionary to store sales for each year
var salesForYears = new Dictionary<int, decimal>();
// Populate the dictionary with sales for each year
for (int year = currentYear - numberOfPastYears + 1; year <= currentYear; year++)
{
salesForYears[year] = salesByYear.FirstOrDefault(s => s.Year == year)?.Sales ?? 0;
}
// Create message to display sales by year
StringBuilder message = new StringBuilder();
message.AppendLine("Sales by Year:");
foreach (var kvp in salesForYears)
{
message.AppendLine($"Year: {kvp.Key}, Sales: {kvp.Value}");
}
// Display the message box
MessageBox.Show(message.ToString(), "Sales by Year", MessageBoxButtons.OK, MessageBoxIcon.Information);
EDIT, this is basically the same query as @Dnyanraj_Patil. His is slightly more straightforward (not bothering with casting dates into ints), but the gist is identical.
int numberOfPastYears = 5; // Specify the number of past years you want to consider
int currentYear = DateTime.Now.Year;
DateTime startDate = new DateTime(currentYear - numberOfPastYears + 1, 1, 1);
DateTime endDate = new DateTime(currentYear + 1, 1, 1); // Next year's start date
var salesByYear = Db.OrderRel
.Where(r => r.Company == Session.CompanyID
&& r.PartNum == ttJobHead_xRow.PartNum
&& r.ReqDate >= startDate
&& r.ReqDate < endDate)
.GroupBy(r => r.ReqDate.Year)
.Select(group => new
{
Year = group.Key,
Sales = group.Sum(r => r.OurJobShippedQty + r.OurStockShippedQty)
})
.ToList();
When I try to compile it errors with:
The type arguments for method ‘Queryable.GroupBy<TSource, TKey>(IQueryable, Expression<Func<TSource, TKey>>)’ cannot be inferred from the usage. Try specifying the type arguments explicitly.