Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List array duplicates with count

Tags:

arrays

c#

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
like image 360
Ahsan Attari Avatar asked Oct 20 '11 07:10

Ahsan Attari


People also ask

How do you count duplicates in array?

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 .

How do you use count to find duplicates?

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).

Can array list have duplicates?

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.


2 Answers

LINQ makes this easy:

Dictionary<string, int> counts = array.GroupBy(x => x)
                                      .ToDictionary(g => g.Key,
                                                    g => g.Count());
like image 191
Jon Skeet Avatar answered Oct 20 '22 18:10

Jon Skeet


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.

like image 24
Anders Forsgren Avatar answered Oct 20 '22 18:10

Anders Forsgren