【问题标题】:sorting listviewitems in different groups in c#在c#中对不同组中的listviewitems进行排序
【发布时间】:2013-09-03 03:55:56
【问题描述】:

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

提前致谢

【问题讨论】:

  • 您想将它们分组到集合中吗?或者您想直观地对它们进行分组(以便您可以看到ListView 中的每个组)?
  • 发布一个不清楚的问题、没有任何示例代码、没有显示您尝试过的内容、没有说明您在哪里遇到问题尤其是如果您随后消失的话,这不是很有礼貌几个小时,所以要求澄清的人没有得到任何答案。
  • 没有代码可以分享。我只需要合乎逻辑的帮助。我仍然无法弄清楚我应该从哪里开始。 @KingKing,是的,我想对 in 集合进行分组,它不需要在视觉上显示

标签: c# winforms listview sorting collections


【解决方案1】:

您可以使用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);

【讨论】:

    【解决方案2】:

    如果你使用ObjectListView——一个围绕标准.NET ListView 的开源包装器,ListView 的生活会简单得多。

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

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

    这给出了这个:


    (来源:sourceforge.net

    只需多做一点工作,您就可以像这样创建一些花哨的东西:


    (来源:sourceforge.net

    【讨论】:

      猜你喜欢
      • 2019-10-16
      • 2012-04-12
      • 2011-04-23
      • 2013-12-24
      • 2013-08-05
      • 2018-06-06
      • 2021-11-18
      • 1970-01-01
      相关资源
      最近更新 更多