【问题标题】:How do I divide a list into groups and store the indices?如何将列表分组并存储索引?
【发布时间】:2010-07-08 09:40:35
【问题描述】:

我有一个包含 6 个值的列表框。使用按钮可以将新项目插入到列表框中。我可以使用我添加的其他按钮上下移动所有这些项目。为了便于理解,我们将新创建的项目(我想充当组/分隔符)称为“组”。我想要完成的是存储组之间的项目。例如通过SortedDictionary<int itemIndex, string group>。一个例子(注意括号内的数字是索引):

Group 1 [0]
Item 1 [1]
Item 2 [2]
Item 3 [3]
Group 2 [4]
Item 4 [5]
Item 5 [6]
Group 3 [7]
Item 6 [8]

字典可能如下所示:

1, "group 1"
2, "group 1"
3, "group 1"
5, "group 2"
6, "group 2"
8, "group 3"

第一个数字是列表框中的项目索引,第二个(字符串)是它所属的组。

所以我的问题是:如何循环列表框以检查哪些项目属于哪个组?如果有更简单的方法(使用与列表框不同的控件),我也很乐意尝试。

【问题讨论】:

    标签: c# listbox sorteddictionary


    【解决方案1】:

    如果您的意思是 winforms,ListView 内置了.Groups(每个ListViewGroup),每个ListViewItem 都有一个.Group。这应该使您在代码中所需的内容变得简单,并且对用户来说直观直观。

    请注意,仅当.ViewView.Details.ShowGroupstrue 并且启用了视觉样式(Application.EnableVisualStyles(),通常在Main())时才会显示组。

    【讨论】:

    • 感谢您的回复。这肯定会使它更容易,但我想坚持与列表框相同的布局。有没有办法让ListView 看起来像一个?
    【解决方案2】:

    我自己解决了这个问题,方法如下:

            // Create string to save last 'used' group in.
            string lastGroup = string.Empty;
    
            // Create counter to check what index we are at in the ListBox.
            int i = 0;
    
            // Create a dictionary to store <string Item, string Group>.
            Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
    
            // Loop every item (as string) in the ListBox.
            foreach (string o in lbxMain.Items)
            {
                // If the item is a group:
                if (o.StartsWith("Group:"))
                    // Put the name of the item into the lastGroup variable so we know where to put the items in.
                    lastGroup = lbxMain.Items[i].ToString();
    
                // If the item is an item:
                if (o.StartsWith("Item:"))
                    // Put the item into a dictionary with the lastGroup variable saying what group it's part of.
                    dictionary .Add(o + " " + i, lastGroup);
    
                // Increase i so we keep an eye on the indices.
                i++;
            }
    

    如果你只想要代码:

            string lastGroup = string.Empty;
            int i = 0;
            Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
    
            foreach (string o in lbxMain.Items)
            {
                if (o.StartsWith("Group:"))
                    lastGroup = lbxMain.Items[i].ToString();
                if (o.StartsWith("Item:"))
                    dictionary.Add(o + " " + i, lastGroup);
                i++;
            }
    

    【讨论】:

      猜你喜欢
      • 2017-07-05
      • 2023-03-17
      • 1970-01-01
      • 2021-11-30
      • 2018-10-13
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 2014-03-08
      相关资源
      最近更新 更多