I have an array which contains the following results
red
red
red
blue
blue
Green
White
Grey
and I want to get duplicate count of every value of array, for example:
red Count=3
blue Count=2
Green Count=1
White Count=1
Grey Count=1
To count the duplicates in an array:Declare an empty object variable that will store the count for each value. Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .
Tip: If you want to count the duplicates in the whole Column, use this formula =COUNTIF(A:A, A2) (the Column A indicates column of data, and A2 stands the cell you want to count the frequency, you can change them as you need).
ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.
LINQ makes this easy:
Dictionary<string, int> counts = array.GroupBy(x => x)
.ToDictionary(g => g.Key,
g => g.Count());
Add them to a Dictionary:
Dictionary<string, int> counts = new Dictionary<string, int>();
foreach(string s in list)
{
int prevCount;
if (!counts.TryGet(s, out prevCount))
{
prevCount.Add(s, 1);
}
else
{
counts[s] = prevCount++;
}
}
Then counts contains the strings as keys, and their occurence as values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With