在c#中对不同组中的listviewitems进行排序

时间:2013-08-30 12:09:08

标签: c# winforms listview sorting collections

需要一个小的逻辑帮助: 我有一个listview项的集合,需要根据其类别(listviewitem.tag.tostring())分类在不同的组中 例如:我在列表视图中有10个项目,标签上有“食物”蔬菜“饮料”等等。现在我想要带有这些标签的集合中的物品。

提前致谢

2 个答案:

答案 0 :(得分:0)

您可以使用Dictionary<string,List<ListViewItem>>来存储群组,Key是群组密钥,可以是foodvegetablesdrinks,... (类别名称)。 Value是相应类别中的项目列表。

var groups = listView1.Items.OfType<ListViewItem>()
                      .GroupBy(e=>e.Tag.ToString())
                      .ToDictionary(k=>k.Key, v=>v.ToList());
//Then to access a category's items, just pass in the category name into the Dictionary like this
var food = groups["food"];//this is a List<ListViewItem> of items in the category 'food'
//try printing the items
foreach(var f in food)
   System.Diagnostics.Debug.Print(f.Text);

答案 1 :(得分:0)

如果使用ObjectListView - 一个围绕标准.NET ListView的开源包装器,使用ListView的生活会更加简单。

例如,启用分组是一行,它告诉控件每行属于哪个组:

lastPlayedColumn.GroupKeyGetter = delegate(object rowObject) { 
    Song song = (Song)rowObject; 
    return new DateTime(song.LastPlayed.Year, song.LastPlayed.Month, 1); 
};

这给出了这个:

ObjectListView with groups http://objectlistview.sourceforge.net/cs/_images/gettingstarted-example52.png

只需多做一点工作,你就可以创造出像这样的东西:

ObjectListView with fancy groups http://objectlistview.sourceforge.net/cs/_images/group-formatting.png