Count unique values in ArrayList C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • GTXY20
    New Member
    • Oct 2007
    • 29

    Count unique values in ArrayList C#

    Hi all,

    I have an ArrayList1 of multiple values. Here is an exaple of the a potential ArrayList1:

    a,a,b,,c,a,b,c, c,c,a,b

    Does anyone have any suggestion whereby I could output the count for wach unique item:

    a=4
    b=3
    c=4

    I have done this in python with a defaultdict(int ) and was wondering if there was a quick way in C# to do this other than creating another ArrayList2 containing a unique set of the items from all od the items in ArrayList1 and then iterating through ArrayList1 counting the values for i where i is drevied from ArrayList2.

    Any guidance or a starting point is much appreciated.

    G.
  • GTXY20
    New Member
    • Oct 2007
    • 29

    #2
    The list of values were kept in a dictionary so I have a dictionary with a key value pair where the value is a list of items.

    Code:
    data = new Dictionary<string, List<string>>
    I ended up placing the items from the value list of the dictionary into two additonal lists a list of distinct values (itemsunique) and then used a foreach loop on a complete list of all the values for all keys in the (allitems):

    Code:
    List<string> allitems = new List<string>();
    List<string> itemsunique = new List<string>();
    
    foreach (KeyValuePair<string, List<string>> s in data)
    {
    foreach (string h in s.Value)
    {
    allitems.Add(h);
    allitems.Sort();
                           
    if (!itemsunique.Contains(h))
    {
    itemsunique.Add(h);
    itemsunique.Sort();
    }
    
    }
    }
    
    
    int count = 0;
    foreach (string y in itemsunique)
    {
    count = allitems.count(n=> n == y);
    Console.Writeline("{0}={1} ", y, count);
    }
    However I will have several lists that I will need to apply this to and afraid that this will be memory intensive if I have to do with each list considering some lists will be quite large with over 100k items.

    Any suggestions or comments are appreciated.

    Thanks.

    g.

    Comment

    • GTXY20
      New Member
      • Oct 2007
      • 29

      #3
      Further I was able to do the same using a hashtable:

      Code:
      Hashtable items = new Hashtable();
      if (!items.Contains(itemfromlist))
             items.Add(itemfromlist, 1);
      else
             items[itemfromlist] = (int) items[itemfromlist]+1

      Comment

      Working...