List array duplicates with count

Solution 1:

LINQ makes this easy:

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

Solution 2:

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.

Solution 3:

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

Solution 4:

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