Solved

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

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Refresh Datagridview from another form 1 28
dynamic menu in asp.net c# 11 31
Long URL in SMS 6 24
XAML: Layout 8 10
Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

743 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

11 Experts available now in Live!

Get 1:1 Help Now