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.
I need to know:
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.
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());