Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2004-03-20
2
Medium Priority
?
393 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

636 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