Reputation: 409
ListView like this
Name | IP | Port
--------------------------------
Alice | 192.168.0.1 | 1000
Bob | 192.168.0.1 | 1000
Carol | 192.168.0.1 | 1000
Dave | 192.168.0.2 | 2000
Eve | 192.168.0.2 | 2000
I want grouping by IP like {Alice, Bob, Carol} and {Dave, Eve}
If it System.Collections.Generic.List
, I use FindAll
.
But it is ListViewItemCollection
, How can I grouping?
The way I can think of is to create a new List by for loop with ListViewItemCollection
.
Is there any other way?
Upvotes: 1
Views: 1605
Reputation:
To group the ListViewItem objects in a ListView control:
Create a grouping method to apply that:
private void GroupListViewItems(int columnIndex)
{
if (!listView1.Columns.Cast<ColumnHeader>()
.Select(c => c.Index).Contains(columnIndex))
return;
listView1.BeginUpdate();
listView1.Groups.Clear();
var groups = listView1.Items.Cast<ListViewItem>()
.GroupBy(x => x.SubItems[columnIndex].Text);
foreach(var group in groups.OrderBy(x => x.Key))
{
var g = new ListViewGroup(group.Key);
listView1.Groups.Add(g);
group.ToList().ForEach(x => x.Group = g);
}
listView1.Columns.Cast<ColumnHeader>().ToList().ForEach(x => x.Width = -2);
listView1.EndUpdate();
}
... and maybe an overload to pass the columns by their names:
private void GroupListViewItems(string columnName)
{
var columnHeader = listView1.Columns.Cast<ColumnHeader>()
.FirstOrDefault(x => x.Text.ToLower().Equals(columnName.ToLower()));
if (columnHeader != null)
GroupListViewItems(columnHeader.Index);
}
... call the method and pass the name/index of a ColumnHeader. To ungroup the items, just clear the ListView.Groups property.
Upvotes: 2