Search code examples
c#windowslistviewlistviewitem

Count all duplicates in ListView column. C#


I'm creating a software for a marketplace and want to create a listview that counts all the duplicate values inside a column.

This count will show how many items were oftenly bought by buyers.

This is the concept of the ListView should be. It counts from column of ListView1, and put the duplicates, count it, and display the data inside of ListView2.

Concept

I need to know:

  • How to Count all the duplicated value inside the "Purchased Items" column.
  • And display the count result inside another ListView with the value itself.

Note: In this case, the value inside the "Name" is an Item and the "Purchased Items" is a Subitem. Those data were from simply typing in a textbox and clicking on a button.


Solution

  • Group the items of the input ListView by the values of the second ColumnHeader (index = 1) to get IEnumerable<IGrouping<string, ListViewItem>>, then use the elements (of type IGrouping<string, ListViewItem>) Key property and Count method to create the ListViewItem objects of the output ListView.

    Here's a one liner:

    listView2.Items.AddRange(listView1.Items
        .Cast<ListViewItem>()
        .GroupBy(x => x.SubItems[1].Text, StringComparer.OrdinalIgnoreCase)
        .Select(x => new ListViewItem(new[] { x.Key, x.Count().ToString() }))
        .ToArray());