Counting instances in c# (keeping a tally)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • trd79
    New Member
    • Apr 2008
    • 6

    Counting instances in c# (keeping a tally)

    Hi,

    I am reading a database which is returning a list of dates. I need to count the instances of each date and store in an array or similar.
    I don't know how many dates I will be getting, or how many different ones.

    In Perl I would so something like this
    for(`getdata`){
    $array{$1}++;
    }

    need something that looks like this:

    while (dReader.Read() )
    {
    Array['dReader[0].ToString()']++;
    }


    Any ideas?
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by trd79
    Hi,

    I am reading a database which is returning a list of dates. I need to count the instances of each date and store in an array or similar.
    I don't know how many dates I will be getting, or how many different ones.

    In Perl I would so something like this
    for(`getdata`){
    $array{$1}++;
    }

    need something that looks like this:

    while (dReader.Read() )
    {
    Array['dReader[0].ToString()']++;
    }


    Any ideas?
    You could use a System.Collecti ons.Hashtable<D ateTime, int>.

    Comment

    • trd79
      New Member
      • Apr 2008
      • 6

      #3
      Originally posted by r035198x
      You could use a System.Collecti ons.Hashtable<D ateTime, int>.
      Many thanks,

      will try that.

      Comment

      • trd79
        New Member
        • Apr 2008
        • 6

        #4
        Hi,

        Have tried using a hashtable as suggested.

        Currently looks like this (and seems to work)

        Code:
        Hashtable sessions = new Hashtable();
        while (dReader.Read())
                {
                    DateTime date = DateTime.Parse(dReader[0].ToString());
                    sessions[date] = (sessions.ContainsKey(date)) ? (int)sessions[date] + 1 : 1;
                }
        Is this the best way of doing it?

        Comment

        Working...