Villi Katrih
Villi Katrih

Reputation: 389

Linq add same items in the same list

So I have a class of products:

class Product{
    public int id;
    public int price;
    public string product_name;
}

var BoughtProductList = new List<Product>();
BoughtProductList .Add(new Product() { id = 1, price = 3 product_name = "orange" });
BoughtProductList .Add(new Product() { id = 2, price = 2 product_name = "apple" });
BoughtProductList .Add(new Product() { id = 2, price = 2 product_name = "apple" });
BoughtProductList .Add(new Product() { id = 3, price = 3 product_name = "banana" });

Now I want to put it in a table so it will show me all the bought products, but i dont want to see the apple product twice. How can i go over that list in linq and without creating a new instance of that class and add the same product id's to see the sum of money i got selling that apple in that list.

Upvotes: 1

Views: 1521

Answers (3)

Liam McInroy
Liam McInroy

Reputation: 4366

var newBoughtProductList = new List<Product>();//create new list

for (int i = 0; i < BoughtProductList.Count; i++)//search old list
{
    Product currentProduct = BoughtListProduct[i];//get current product

    if (!newBoughtProductList.Contains(currentProduct)) //see if duplicate
        newBoughtProductList.Add(currentProduct);       //add product

    else 
    {
        int copyingProduct = BoughtProductList.FindIndex(currentProduct);
        //get duplicates index

        newBoughtProductList[copyingProduct].price += 
           newBoughtProductList[copyingProduct].price;//add to price of duplicate
    }
}

This basically searches the list and adds none duplicates, then if something is a duplicate, it increases the price by the duplicate's price. Note: This does not use linq (but you probably knew that) Hope this helps!

Upvotes: 1

Jon Hanna
Jon Hanna

Reputation: 113242

from produce in BoughtProductList
group produce.price by new {produce.id, produce.product_name} into grp
select new{grp.id, grp.product_name, TotalPrice = grp.Sum()};

Upvotes: 5

Servy
Servy

Reputation: 203821

What you want to do is perform a GroupBy on the product's id property. Once you do that you can add the id and product_name from each group and know that it will be distinct. You can also Sum over the price of each group (or just multiply the count by the price) to get the sum of money earned selling that product.

Upvotes: 1

Related Questions