【问题标题】:Find if a ListViewGroup already exists查找 ListViewGroup 是否已存在
【发布时间】:2020-06-12 19:45:59
【问题描述】:

经典Windows窗体类型的界面,我有两个ListView,一个在左边(SongsAvailable),一个在右边(SongsInLibrary)。在左侧列表中选择一个条目,单击一个按钮将其添加到右侧列表中,但将其放在右侧组中(如果存在)。我有这个代码

private void AddSelected(Object sender, EventArgs e)
{
    bool rc = false;
    foreach (ListViewItem item in SongsAvailable.SelectedItems)
    {
        var s = item.SubItems[0].Text.Substring(0, 1);
        TestGroup = new ListViewGroup(s, s);
        rc = SongsInLibrary.Groups.Contains(TestGroup);
        if (!rc) { // create a new group and add it  }
        SongsInLibrary.Items.Add(new ListViewItem(new[] { item.SubItems[0].Text, item.SubItems[1].Text, item.SubItems[2].Text, item.SubItems[3].Text }, ListGroup ));
    }
}

return rc 始终为 false(这并不让我感到惊讶,新的 ListViewGroup 不能已经存在于 Groups 集合中)所以我总是添加新的组。 “包含”的文档也非常简洁。如果没有遍历所有组,我如何找到 A 组是否已经存在?

【问题讨论】:

  • 如果您将TestGroup 设置为等于new ListViewGroup 实例,您如何期望它等于某个其他实例(Contains 需要返回true)?
  • 我确实在我的问题中提到了它。
  • 我不清楚您是如何发现需要搜索的组(s 应该代表什么?),但从the documentation 看来,ListViewGroupCollection类(这是SongsInLibrary.Groups 的类型)实现IList,因此您应该能够遍历项目以使用普通循环找到您想要的项目。你试过吗?
  • 例如,我有一首以字母“A”开头的歌曲。我想把它放在“A”组中。所以是的,我可以在 lvm.groups 中执行类似(伪代码)foreach 组的操作,如果 group.name.equals("A"),则使用该组添加项目。如果我浏览了所有组但没有找到“A”,则添加一个新组并使用该组添加项目(结束伪代码)。但这似乎非常低效,而且绝对不雅。

标签: c# winforms collections


【解决方案1】:

我对这些ListViewGroupListViewItem 课程了解不多,但由于没有其他人回答,这里至少有一种方法:

  1. 使用Cast 方法(来自System.Linq)将ListViewGroupCollection 转换为IEnumerable<ListViewGroup>
  2. 获取具有我们要查找的标头的 FirstOrDefault
  3. 如果该组不存在,则创建一个新组并将其添加到SongsInLibrary.Groups
  4. SongsAvailable 中删除项目(似乎需要这样做才能将其添加到新组)
  5. 将项目的Group 设置为我们希望它加入的组
  6. 将该项目添加到我们的SongsInLibrary 收藏中

这样做可以避免使用new Group 调用Contains 的问题(永远不会存在)

例如:

foreach (ListViewItem item in SongsAvailable.SelectedItems)
{
    // Determine the group we want to add this to (the first letter of the item)
    var groupHeader = item.Text.Substring(0, 1);

    // Get the first group that matches, or null if it's not there
    var group = SongsInLibrary.Groups.Cast<ListViewGroup>()
        .FirstOrDefault(g => g.Header == groupHeader);

    // If it's not there, create it and add it
    if (group == null)
    {
        group = new ListViewGroup(groupHeader);
        SongsInLibrary.Groups.Add(group);
    }

    // Move the song to the goup and add the song to the library
    SongsAvailable.Items.Remove(item);
    item.Group = group;
    SongsInLibrary.Items.Add(item);
}

可能有更好的方法,但从the documentationListView.Groups 的快速浏览来看,它们似乎不太容易使用。

【讨论】:

  • 这就是我想要的。作为额外的奖励,我重新考虑将这首歌添加到列表中。我正在创建一个新对象(所以它会在两者中,这意味着我必须先检查它是否已经存在。)在填充原始列表和从右侧移回时,我将不得不重新做一些事情向左,但这不应该是什么大事。
猜你喜欢
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 2015-04-28
相关资源
最近更新 更多