How to generate balance seed using LINQ query

jewel 1,026 Reputation points
2024-10-10T16:16:23.6533333+00:00
I have some data on the left side of the image below. I want to create a balance seed like the one on the right side using 
Screenshot (22).png
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,029 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 66,866 Reputation points
    2024-10-12T16:17:41.55+00:00

    sorry, minor bug (I edited the post and updated)

    n.balance = n.balance + p.Sum(r => r.balance);

    with

    n.balance = n.balance + p.LastOrDefault()?.balance ?? 0;

    only need the previous balance, not recalc running total

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 66,866 Reputation points
    2024-10-10T19:25:35.7733333+00:00

    you need a class for the result data:

    class DataDisplay
    {
    	public string text {get; set;} 
    	public Decimal credited {get; set;} 
    	public Decimal debited {get; set;} 
    	public Decimal balance {get; set;} 
    }
    

    then it pretty simple.

    var list = getInputData();
    var previousBalanceDate = new DateTime(2024, 3,16);
    
    var resultList = list
    	.OrderBy(r => r.date)
    	.Select(r => new DataDisplay
    	{
    		text = r.date < previousBalanceDate ? "previous balance" : r.date.ToString("dd-MMM-yy"),
    	    credited = r.credited,
    	    debited = r.debited,
    		balance = r.credited - r.debited
    	})
    	.Aggregate(new List<DataDisplay>() as IEnumerable<DataDisplay>, (p, n) =>
    	{
    		n.balance = n.balance + p.LastOrDefault()?.balance ?? 0;
    		if (n.text == "previous balance" && p.FirstOrDefault()?.text == "previous balance")
    		{
    			p.First().balance = n.balance;
    			return p;
    		}
    		return p.Append(n);
    	});
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.