| Pete Dashwood 2007-02-02, 6:55 pm |
|
"andrewmcdonagh" <andrewmcdonagh@gmail.com> wrote in message
news:1170416819.673830.134600@k78g2000cwa.googlegroups.com...
> On Feb 2, 1:42 am, LX-i <lxi0...@netscape.net> wrote:
<snip>
[color=darkred]
> Quick suggestion about your COBOL keywords.... instead of using an
> XML file, or raw array, you'll get much better (near constant time)
> lookup performance if you use a single in memory HashTable collection.
> Hashtables use two objects, one is a 'key' and the other a 'value'.
> Unfortunately the c# library doesn't have a Java HashSet, which has
> the same behaviour as hastables, but is for storing keys only.
>
Er...not necessarily... :-)
Although C# supports the Hashtable function (so Java folks can remain
comfortable...:-)), it is much better to use the C# Dictionary Class
because it doesn't require boxing and unboxing of objects.
Furthermore, the Dictionary Class DOES support a collection of Keys and
Values as separate entities, if you want this.
I have no issue with the approach (it's very good), but would strongly
recommend Dictionary, rather than Hashtable.
(Check out the VS 2005 Help index for "Dictionary"...)
> // Create a new hash table.
> Hashtable cobolKeywords = new Hashtable();
>
> // Add some elements to the hash table.
> // hashtable does not allow
> // duplicate keys, but values can be duplicates.
> cobolKeywords.Add("ACCEPT", "ACCEPT ");
> cobolKeywords.Add("ACCESS", "ACCESS");
> cobolKeywords.Add("ACQUIRE", "ACQUIRE");
> cobolKeywords.Add("ADD", "ADD");
> ...
>
> // The Item property is the default property, so you
> // can omit its name when accessing elements.
> Console.WriteLine("The value for Add = ", cobolKeywords["ADD"] );
>
> // ContainsKey can be used to test keys before inserting them.
> if (! cobolKeywords.ContainsKey("BEFORE"))
> {
> cobolKeywords.Add("BEFORE", "BEFORE");
> Console.WriteLine("Value added for key = \"ht\": {0}",
> cobolKeywords["ht"]);
> }
>
> // When you use foreach to enumerate hash table elements,
> // the elements are retrieved as KeyValuePair objects.
>
> foreach( DictionaryEntry de in cobolKeywords)
> {
> Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
> }
>
> // To get the values alone, use the Values property.
> ICollection valueColl = cobolKeywords.Values;
>
> // The elements of the ValueCollection are strongly typed
> // with the type that was specified for hash table values.
>
> foreach( string s in valueColl )
> {
> Console.WriteLine("Value = {0}", s);
> }
>
Really good sample code above, Andrew. Good stuff!
Pete.
|