Search code examples
c#listboxsorteddictionary

How do I divide a list into groups and store the indices?


I have a list box which holds, say, 6 values. Using buttons it's possible to insert new items into the list box. I can move all of these items up and down using other buttons I've added. For the purpose of understanding we'll call the newly created items (which I want to act as groups/dividers) "groups". What I want to accomplish is to have the items between the groups stored. For example through a SortedDictionary<int itemIndex, string group>. An example (note that the bracketed number is the index):

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]

The dictionary could look like this:

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

Where the first number is an item index in the list box and the second (string) is the group it falls under.

So my question is: how do I loop the list box in such a way that I can check which items fall under what group? If there's an easier way of doing it (using a different control than a list box) I'm happy to try that too.


Solution

  • I've managed to solve it myself and this is how:

            // 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++;
            }
    

    And if you just want the code:

            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++;
            }