Search code examples
c#arraylisticomparable

Compare/count values in a System.Collections.ArrayList


I'm scrubbing 5 files for a specific value. I dont anticipate any different values, BUT since this is for my own educational purposes, I would like the application to count, compare and print the most popular value.

for example:

ArrayList arrName = new ArrayList();
arrName.Add("BOB")
arrName.Add("JOHN")
arrName.Add("TOM")
arrName.Add("TOM")
arrName.Add("TOM")

The result I would like is going to be TOM but being a novice, I really dont know how to move forward.

Any thoughts, suggestions or examples are greatly appreciated. Thank you.


Solution

  • You can use a Dictionary (.NET 2.0+) to hold the repeated count of each value:

    Dictionary<string, int> counts = new Dictionary<string, int>();
    foreach (string name in arrName) {
       int count;
       if (counts.TryGetValue(name, out count)) {
          counts[name] = count + 1;
       } else {
          counts.Add(name, 1);
       }
    }
    
    // and then look for the most popular value:
    
    string mostPopular;
    int max = 0;
    foreach (string name in counts.Keys) {
       int count = counts[name];
       if (count > max) {
           mostPopular = name;
           max = count;
       }
    }
    
    // print it
    Console.Write("Most popular value: {0}", mostPopular);
    

    If you're using C# 3.0 (.NET 3.5 +) then use:

    var mostPopular = (from name in arrName.Cast<string>()
                       group name by name into g
                       orderby g.Count() descending
                       select g.Key).FirstOrDefault();
    
    Console.Write("Most popular value: {0}", mostPopular ?? "None");