i have two lists of class type TestClass. I just need to aggregate two lists.
public class TestClass
{
private string _fan;
private string _prefix;
private decimal _amount;
#region Properties
public string Fan
{
get { return _fan; }
set { _fan = value; }
}
public string Prefix
{
get { return _prefix; }
set { _prefix = value; }
}
public decimal Amount
{
get { return _amount; }
set { _amount = value; }
}
#endregion
}
If Fan and Prefix columns have same value then i just need make them as one column and sum the amount. How to do it?
LIST 1
FAN PREFIX AMOUNT
F1 P1 10
F1 P2 20
F2 P2 50
LIST 2
FAN PREFIX AMOUNT
F1 P1 30
F1 P3 20
F2 P2 30
OUTPUT
FAN PREFIX AMOUNT
F1 P1 40
F1 P2 20
F1 P3 20
F2 P2 80
I need output like this. What is the best way to achieve this?
var l1 = new List<TestClass>
{
new TestClass{Fan = "F1", Prefix = "P1", Amount = 10},
new TestClass{Fan = "F1", Prefix = "P2", Amount = 20},
new TestClass{Fan = "F2", Prefix = "P2", Amount = 50},
};
var l2 = new List<TestClass>
{
new TestClass{Fan = "F1", Prefix = "P1", Amount = 30},
new TestClass{Fan = "F1", Prefix = "P3", Amount = 20},
new TestClass{Fan = "F2", Prefix = "P2", Amount = 30},
};
var result = l1.Concat(l2).GroupBy(f => new { f.Fan, f.Prefix })
.Select(g => new TestClass
{
Fan = g.Key.Fan,
Prefix = g.Key.Prefix,
Amount = g.Sum(_ => _.Amount)
})
.ToList();
//Fan Prefix Amount
//F1 P1 40
//F1 P2 20
//F2 P2 80
//F1 P3 20
First we put the two lists together (List.Concat), then group elements that have the same Fan and Prefix together (GroupBy) and finally we sum up the amounts per group.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With