-2

Hello Stackoverflow community, I have the following problem. I created a listbox with this format (the data is always different):

item1
item2
item1
item2
item1
item3
item1

but now i want to sort this and count it together like that:

4 x item1
2 x item2
1 x item3

I just can't think of a method that would be able to do this with a dynamic text. Thanks for all your help in advance.

ludgard
  • 3
  • 1

1 Answers1

0

Let's say your listBox content consists of strings only or they are distinguishable by their ToString().

You may create a dictionary and add each item to it. Then count them in the value field:

Dictionary<string, int> counts = new Dictionary<string, int>();
foreach(var i in listBox1.Items)
{
    if (!counts.ContainsKey(i.ToString()))
        counts.Add(i.ToString(), 0);
        counts[i.ToString()]++;
    }
}

You may then print them all out similar to this (latest C# version required):

foreach (KeyValuePair<string, int> entry in counts)
    Console.WriteLine($"{entry.Value}x {entry.Key}");

You may find your own solution to sorting the data from the dictionary. Please, be aware of the fact that the data inside of the dictionary cannot be sorted inside of this class, as dictionaries do not keep track of any order. There is however an approach to this with Linq: StackOverflow: how-do-you-sort-a-dictionary-by-value

Community
  • 1
  • 1
oelsardine
  • 96
  • 1
  • 7