Solved

I'm trying to make something like a hashtable / sorted list?

Posted on 2004-03-20
2
354 Views
Last Modified: 2010-04-15
Basically I'm curious how to make something like the DataSet structure where I can call DataSet.Tables[0] or DataSet.Table["maintable"].

I want to load in an array of a custom structure, and be able to reference each structure by their index # or a value as above.
From there I want to do say.. (custom[0].somestring and custom[0].myarray[0]) or (custom["mystring"].somestring custom["mystring"].mrarray[0]).  

the structure might look something like this for example:
{
    string something;
    string[] myarray;
    int[] numbers;
}

Would Using a hash table to reference another hashtable/sortedlist be the only way to come about this solution, or is there an easier method to immitate how other object arrays in c# do it?
0
Comment
Question by:mhertzDEV
2 Comments
 
LVL 12

Accepted Solution

by:
esteban_felipe earned 400 total points
ID: 10642869
Hi mhertzDEV,

You are looking for a class with an indexer. That's a special property that you declare like:
public int this[int index]
{
    get{}
    set{}
}

I wrote a small sample for a class that does something similar of what you are looking for: It keeps a string arrays fors "Keys" and an int array for "Values". You can add items and access them using and index or the key. Check it out:

using System;

namespace ConsoleApplication15
{
      public class CustomArray
      {
            //An array to keep the keys
            private string[] strKeyArray;
            //An array to keep the values
            private int[] intValueArray;
            //A constructor that allow to specify an initial capacity. It will be good to implement one
            //to avoid several redimensions of the arrays
            public CustomArray(int initialCapacity)
            {
                  strKeyArray = new string[initialCapacity];
                  intValueArray = new int[initialCapacity];
            }
            //The default constructor. Both array are declared ot 1 size
            public CustomArray()
            {
                  strKeyArray = new string[1];
                  intValueArray = new int[1];
            }
            //A private method to redimension the arrays in 1 position
            private void expandArrays()
            {
                  string[] tmpKeyArray = new string[strKeyArray.Length +1 ];
                  int[] tmpValueArray = new int[intValueArray.Length +1];
                  for(int i =0;i < tmpKeyArray.Length-1; i++)
                  {
                        tmpKeyArray[i] = strKeyArray[i];
                        tmpValueArray[i] = intValueArray[i];
                  }
                  strKeyArray = (string[])tmpKeyArray.Clone();
                  intValueArray = (int[])tmpValueArray.Clone();
            }
            //A private method to inset a key/value pair at certain positin
            private void add(int position, string key, int value)
            {
                  strKeyArray[position] = key;
                  intValueArray[position] = value;
            }
            //The public method to add key/values pairs
            //It will check if the arrays are full and expand them if so, or will find the first "not filled" position
            public void add(string key, int value)
            {
                  if(strKeyArray[strKeyArray.Length -1] != null)
                  {
                        expandArrays();
                        add(strKeyArray.Length -1,key,value);
                  }
                  else
                  {
                        for(int i = 0; i < strKeyArray.Length; i++)
                        {
                              if(strKeyArray[i] == null)
                              {
                                    add(i,key,value);
                                    break;
                              }
                        }
                  }
            }
            //An indexer that allow access and update to the values array using an int position
            //Will raise an exception if the index is out of bounds
            public int this[int index]
            {
                  get
                  {
                        if(index > strKeyArray.Length -1)
                        {
                              throw(new ApplicationException("Index out of bounds"));
                        }
                        return intValueArray[index];
                  }
                  set
                  {
                        if(index > strKeyArray.Length -1)
                        {
                              throw(new ApplicationException("Index out of bounds"));
                        }
                        intValueArray[index] = value;
                  }
            }
            //An indexer that allow access and update to the values array using a string key.
            //Will raise an excepton if the key is not found
            public int this[string key]
            {
                  get
                  {
                        for(int i = 0; i < strKeyArray.Length; i++)
                        {
                              if(strKeyArray[i] == key)
                              {
                                    return intValueArray[i];
                              }
                        }
                        throw(new ApplicationException("Key not found"));
                  }
                  set
                  {
                        for(int i = 0; i < strKeyArray.Length; i++)
                        {
                              if(strKeyArray[i] == key)
                              {
                                    intValueArray[i] = value;
                                    break;
                              }
                        }
                        throw(new ApplicationException("Key not found"));
                  }
            }
            //A read-only property to know how many elements exists
            public int Count
            {
                  get
                  {
                        return strKeyArray.Length -1;
                  }
            }
      }
      class Class1
      {
            [STAThread]
            static void Main(string[] args)
            {
                  //Create an instance of CustomArray
                  CustomArray objArray = new CustomArray();
                  //Add two key/values pairs
                  objArray.add("test",0);
                  objArray.add("other test",1);
                  //Access the value using the position index
                  Console.WriteLine(objArray[0].ToString());
                  //Access the value using the key
                  Console.WriteLine(objArray["other test"].ToString());
                  //Print the count of values in your object
                  Console.WriteLine(objArray.Count);
            }
      }
}


Be aware that this class should be improved to not return values with null, and that the Count property doesn't "count" the null values if the object was created using a initialCapacity.

This is not the only way to get what you want. You can have a similar class that use a HashTable as a member or even inherits the Hashtable class and add/override the desired functionality. You can also implement your own collection inhereting CollectionBase or implementing ICollection interface. All this mean that you have several options and you should study all them before implementing your code, to fing out which one will give you the easier and more efficient way to achieve your expected results.

Anyway, It was fun to write this little class and show you how to add indexers properties to your class. Good luck & have fun

Esteban Felipe
www.estebanf.com
0
 
LVL 12

Expert Comment

by:dfiala13
ID: 10642955
.NET has a few classes that make this a little more straightforward.

Check out inherting from the DictionaryBase class and CollectionBase class.  Each does all the bookkeeping work down for you, you just need to implement the type specific indexers.  DictionaryBase class would be the proper base for the problem you want to solve.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now