LINQ sum Data Group by Month And Year

jewel 801 Reputation points
2024-04-21T17:12:47.58+00:00

I have Some Data below Image. How Can do this Using LINQ Query.Screenshot (15)

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,187 questions
0 comments No comments
{count} votes

Accepted answer
  1. hossein jalilian 2,985 Reputation points
    2024-04-21T21:15:08.71+00:00

    Thanks for posting your question in the Microsoft Q&A forum.

    You can group the data by month and year and then calculate the sum of each group. Here's how you can do it:

      var result = from credit in credits
                         group credit by new 
    						{ 
    						  Month = credit.Date.Month, 
    						  Year = credit.Date.Year 
    						} into creditGroup                     
                         join debit in debits on new 
    						{ 
    						 Month = creditGroup.Key.Month,
    						 Year = creditGroup.Key.Year
    						}
    						 equals new 
    						{ 
    						   Month = debit.Date.Month, 
    						   Year = debit.Date.Year 
    						} into joinedGroup
                         from debit in joinedGroup.DefaultIfEmpty()
                         select new
                         {
                             Month = creditGroup.Key.Month,
                             Year = creditGroup.Key.Year,
                             Credit1 = creditGroup.Sum(c => c.Credit1),
                             Credit2 = creditGroup.Sum(c => c.Credit2),
                             Debit = debit != null ? debit.DebitAmount : 0,
                             Result = (creditGroup.Sum(c => c.Credit1) + creditGroup.Sum(c => c.Credit2)) - (debit != null ? debit.DebitAmount : 0)
                         };
    
    

    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful