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