Merge Duplicate list entries into one and display quantity in C# -
i have list below.
list<product> productlist = new list<product>(); and product class looks follows.
public class product { public int id { get; set; } public string productname { get; set; } public int quantity { get; set; } } now if user inserts duplicate list entries identified id, how able merge follows
product name qty coke 2 pepsi 7
you use linq build new set of products:
var results = productlist .groupby(p => p.id) .select(g => new product { id = g.key, productname = g.first().productname, quantity = g.sum(i => i.quantity) }) .tolist(); if need product names , quantities, can use:
var results = productlist .groupby(p => p.productname) .select(g => new { productname = g.key, quantity = g.sum() }); foreach(var product in results) { console.writeline("{0} {1}", product.productname, product.quantity); }
Comments
Post a Comment