[英]ListView Grouping by Column Value
ListView like this像这样的ListView
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}我想按 IP 分组,例如 {Alice, Bob, Carol} 和 {Dave, Eve}
If it System.Collections.Generic.List
, I use FindAll
.如果是
System.Collections.Generic.List
,我使用FindAll
。
But it is ListViewItemCollection
, How can I grouping?但它是
ListViewItemCollection
,我该如何分组?
The way I can think of is to create a new List by for loop with ListViewItemCollection
.我能想到的方法是使用
ListViewItemCollection
通过 for 循环创建一个新列表。
Is there any other way?还有其他方法吗?
To group the ListViewItem objects in a ListView control:对ListView控件中的ListViewItem对象进行分组:
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 . ...调用该方法并传递ColumnHeader的名称/索引。 To ungroup the items, just clear the ListView.Groups property.
要取消组合项目,只需清除ListView.Groups属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.