Liverpool
Liverpool

Reputation: 285

Windows Forms - count subitems in listview?

I have this issue, when selected multiple times one product in UI then in listview it apears multiple times...on multiple rows I want to be one row with cappuccino with quantity and it price

enter image description here

I have a list of products:

public List<Product> productsList1;

and then

foreach (var item in productsList)
            {
                //listView1.Items.Add(item.ToString());
                ListViewItem lvi = new ListViewItem(item.Name);

                lvi.SubItems.Add(item.Price.ToString());
                listView1.Items.Add(lvi);
            }

The list has only name of product and it's price.How to in listview to count how much it appears and if we have 2 cappuccino and 1 late to have 2 rows in listview and count their quantity:

Cappuccino ---> 2 ----> 1 Euro

Late -----> 1 >>>> 2 Euro

Upvotes: 0

Views: 346

Answers (1)

jason.kaisersmith
jason.kaisersmith

Reputation: 9650

In Linq you can do a group by and sum.

        var nl = from pl in productsList1
                 group pl by new { pl.Name }  into g
                 select new { Product = g.Key, Quantity = g.Count(), PricePerLine = g.Sum( ss => ss.Price)};

You can then iterate this list

foreach(var item in nl)
{
    ListViewItem lvi = new ListViewItem(item.Name);

    //Quantity
    ListViewItem lvi = new ListViewItem(item.Quantity .ToString());

    //Price per line item
    lvi.SubItems.Add(item.PricePerLine .ToString());
    listView1.Items.Add(lvi);
}

Upvotes: 1

Related Questions