Solved

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

Posted on 2004-03-20
2
361 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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

Suggested Solutions

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

778 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