[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2004-03-20
2
Medium Priority
?
395 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 1600 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses
Course of the Month18 days, 20 hours left to enroll

834 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