Group by in Arrays

Last post 01-16-2007 9:49 PM by Raymond Wen - MSFT. 2 replies.

Sort Posts:

  • Group by in Arrays

    01-16-2007, 4:14 AM
    • Member
      182 point Member
    • BrunoEckeskog
    • Member since 04-11-2006, 6:50 AM
    • Sweden
    • Posts 54

    In a SQL statement you can use something like this:
    select id count(*)  from sales group by id order by 2 desc....

    But I have an Array that I want to do the same with.
    The contens of the Array is like this:

    ITEMS

    2006.41
    2006.40
    2006.40
    2006.40
    2006.41
    2006.41
    2006.40
    2006.47
    2006.40
    2006.45
    2006.42
    2006.41
    2006.41
    2006.41
    2006.43
    2006.41
    2006.41
    2006.43
    2006.41
    2006.41


    And I want a out outprint like this; (ist going to be used in a chart later on)

    ITEMS  COUNT

    2006.40  5  
    2006.41  10
    2006.42  1
    2006.43  2
    2006.45  1
    2006.47  1


    Is there any simple way?

    Thx Bruno

  • Re: Group by in Arrays

    01-16-2007, 5:41 AM
    • Contributor
      3,498 point Contributor
    • MIB426
    • Member since 04-25-2003, 3:19 AM
    • Taiwan or Australia
    • Posts 849
    the best way i found is put them in the arraylist then loop the arralyist to get same object count
    James Wu (MIB426)
    .NET is only way to go
    MCP, MCSE, MCDBA, MCSD, MCAD
  • Re: Group by in Arrays

    01-16-2007, 9:49 PM
    Answer
    Hi,
    Or can you take advantage of HashTable, add them into a hashtable, and its value keeps its count.

    Hashtable ht = new HashTable();
    foreach(object o in array)
    {
          if( ht.Contains(o))
                      { int temp = (int)ht[o]; temp ++; ht[o] = temp;}
          else
                    ht.Add(o,1);
    }
    Then loop through the ht to get each item's count.
    Hope it helps.
Page 1 of 1 (3 items)