Ahsan Attari
Ahsan Attari

Reputation: 1079

List array duplicates with count

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

Upvotes: 13

Views: 21938

Answers (7)

Michal M
Michal M

Reputation: 11

Hashtable ht = new Hashtable();
foreach (string s in inputStringArray)
{
    if (!ht.Contains(s))
    {
        ht.Add(s, 1);
    }
    else
    {
        ht[s] = (int)ht[s] + 1;
    }
}

Upvotes: 0

user2039008
user2039008

Reputation: 11

a little error above, right code is:

string[] arr = { "red", "red", "blue", "green", "Black", "blue", "red" };

var results = from str in arr
              let c = arr.Count( m => str.Contains(m.Trim()))
              select str + " count=" + c;

foreach(string str in results.Distinct())
    Console.WriteLine(str);

Upvotes: 1

Nour Enbabi
Nour Enbabi

Reputation: 30

make another array of counts ....and loop on the original array putting a condition that if it found red increment the 1st cell of the count array ...if it found blue increment the second cell in the count array ....etc. Good Luck .

Upvotes: 0

user529213
user529213

Reputation: 24

I think this should do the trick

    string[] arr = { "red", "red", "blue", "green", "Black", "blue", "red" };

    var results = from str in arr
                  let c = arr.Count( m => str.Contains(m.Trim()))
                  select str + " count=" + str;

    foreach(string str in results.Distinct())
        Console.WriteLine(str);

Output:

red count=3
blue count=2
green count=1
Black count=1

Upvotes: -1

Tadeusz
Tadeusz

Reputation: 6883

Hmm That is a very hard task, but Captain Algorithm will help you! He is telling us that there are many ways to do this. One of them he give me and I give it to you:

Dictionary <object, int> tmp = new Dictionary <object, int> ();

foreach (Object obj in YourArray)
  if (!tmp.ContainsKey(obj))
    tmp.Add (obj, 1);
 else tmp[obj] ++;

tmp.Values;//Contains counts of elements

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499860

LINQ makes this easy:

Dictionary<string, int> counts = array.GroupBy(x => x)
                                      .ToDictionary(g => g.Key,
                                                    g => g.Count());

Upvotes: 34

Anders Forsgren
Anders Forsgren

Reputation: 11101

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.

Upvotes: 1

Related Questions