Reputation: 45
I've a List of custom objects called Product: List
class Product
{
string Key1 {get; set;}
string Key2 {get; set;}
int Count1 {get; set;}
int Count2 {get; set;}
}
I'm combining multiple Product lists and I need to create a new list which will have sum values for each of the Count properties. For e.g.
List 1:
"Key1", "Key2", 1, 2
"Key2", "Key3", 3, 4
List 2:
"Key1", "Key2", 5, 6
"Key2", "Key3", 7, 8
So my new List should be:
New List:
"Key1", "Key2", 6, 8
"Key2", "Key3", 10, 12
Can someone help me on this please?
Thanks.
Upvotes: 0
Views: 49
Reputation: 4046
List<Product> lst1 = new List<Product>();
List<Product> lst2 = new List<Product>();
lst1.Add(new Product() {Key1 = "K1",Key2 ="K2", Count1 =1, Count2=2 });
lst1.Add(new Product() { Key1 = "K2", Key2 = "K3", Count1 = 3, Count2 = 4 });
lst2.Add(new Product() { Key1 = "K1", Key2 = "K2", Count1 = 5, Count2 = 6});
lst2.Add(new Product() { Key1 = "K2", Key2 = "K3", Count1 = 7, Count2 = 8 });
// Way 1
var l = lst1.Join(lst2, l1 => l1.Key1, l2 => l2.Key1,
(lt1, lt2) => new Product { Key1 = lt1.Key1, Key2 = lt1.Key2, Count1 = lt1.Count1 + lt2.Count1, Count2 = lt1.Count2 + lt2.Count2 } ).ToList() ;
// Way 2
var result = lst1.Join(lst2, x => new { x.Key1, x.Key2 },
y => new { y.Key1, y.Key2 }, (x, y) =>
new Product { Key1 = x.Key1, Key2 = x.Key2, Count1 = x.Count1 + y.Count1, Count2 = x.Count2 + y.Count2 }).ToList();
Upvotes: 0
Reputation: 81493
You can do this
var list1 = new List<Product>()
{
new Product(){Key1 = "Key1", Key2 ="Key2", Count1 = 1, Count2 = 2},
new Product(){Key1 = "Key2", Key2 ="Key3", Count1 = 1, Count2 = 2}
};
var list2 = new List<Product>()
{
new Product(){Key1 = "Key1", Key2 ="Key2", Count1 = 6, Count2 = 8},
new Product(){Key1 = "Key2", Key2 ="Key3", Count1 = 10, Count2 = 12}
};
var result = list1.Concat(list2)
.GroupBy(x => new {x.Key1,x.Key2})
.Select(x => new
{
x.Key.Key1,
x.Key.Key2,
SumCount1 = x.Sum(y => y.Count1),
SumCount2 = x.Sum(y => y.Count2)
}).ToList();
Output
Key1, Key2, 7, 10
Key2, Key3, 11, 14
Additional Resources
Adds the elements of the specified collection to the end of the List.
Enumerable.GroupBy Method (IEnumerable, Func, Func)
Groups the elements of a sequence according to a specified key selector function and projects the elements for each group by using a specified function.
Enumerable.Concat Method (IEnumerable, IEnumerable)
Concatenates two sequences.
Upvotes: 2