C# | Adding an element into the Hashtable - GeeksforGeeks (2024)

Skip to content

C# | Adding an element into the Hashtable - GeeksforGeeks (1)

Last Updated : 01 Feb, 2019

Improve

Improve

Like Article

Like

Save

Report

The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Add(Object, Object) Method is used to adds an element with the specified key and value into the Hashtable.

Syntax:

public virtual void Add(object key, object value);

Parameters:

key: It is the specified key of the element to add of type System.Object.

value: It is the specified value of the element to add of type System.Object. The value can be null.

Exceptions:

  • ArgumentNullException : If the key is null.
  • ArgumentException : If an element with the same key already exists in the Hashtable.
  • NotSupportedException : Either Hashtable is read-only or Hashtable has a fixed size.

Below given are some examples to understand the implementation in a better way :

Example 1 :

// C# code for adding an element with the

// specified key and value into the Hashtable

using System;

using System.Collections;

class GFG {

// Driver code

public static void Main()

{

// Creating a Hashtable

Hashtable myTable = new Hashtable();

// Adding elements in Hashtable

myTable.Add("g", "geeks");

myTable.Add("c", "c++");

myTable.Add("d", "data structures");

myTable.Add("q", "quiz");

// Get a collection of the keys.

ICollection c = myTable.Keys;

// Displaying the contents

foreach(string str in c)

Console.WriteLine(str + ": " + myTable[str]);

}

}

Output:

d: data structuresc: c++q: quizg: geeks

Example 2:

// C# code for adding an element with the

// specified key and value into the Hashtable

using System;

using System.Collections;

class GFG {

// Driver code

public static void Main()

{

// Creating a Hashtable

Hashtable myTable = new Hashtable();

// Adding elements in Hashtable

myTable.Add("4", "Even");

myTable.Add("9", "Odd");

myTable.Add("5", "Odd and Prime");

myTable.Add("2", "Even and Prime");

// Get a collection of the keys.

ICollection c = myTable.Keys;

// Displaying the contents

foreach(string str in c)

Console.WriteLine(str + ": " + myTable[str]);

}

}

Output:

5: Odd and Prime9: Odd2: Even and Prime4: Even

Reference:



Improve

Please Login to comment...

Similar Reads

C# | Check if a Hashtable is equal to another Hashtable

The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Syntax: myTable1.Equals(myTable2) Here, myTable1 and myTable2 are the two Hashtables which is to be checked. Below given are some examples to understand the implementation in

2 min read

C# | Remove the element with the specified key from the Hashtable

The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Remove(Object) Method is used to remove the element with the specified key from the Hashtable. Syntax: public virtual void Remove (object key); Parameter: key: It i

2 min read

C# | Check if Hashtable has a fixed size

Hashtable.IsFixedSize Property is used to get a value which indicates whether the Hashtable has a fixed size or not. Syntax: public virtual bool IsFixedSize { get; } Return Value: This property returns true if the Hashtable has a fixed size otherwise it returns false. The default is false. Below programs illustrate the above-discussed property: Exa

2 min read

C# | Check if the Hashtable contains a specific Key

The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.ContainsKey(Object) Method is used to check whether the Hashtable contains a specific key or not. Syntax: public virtual bool ContainsKey(object key); Parameter: ke

2 min read

C# | Check if the Hashtable contains a specific Value

The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.ContainsValue(Object) Method is used to check whether the Hashtable contains a specific value or not. Syntax: public virtual bool ContainsValue(object value); Param

2 min read

C# | Remove all elements from the Hashtable

The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Clear Method is used to remove all elements from the Hashtable. Syntax: myTable.Clear() Here myTable is the name of the Hashtable. Exceptions: This method will give

2 min read

C# | Count the number of key/value pairs in the Hashtable

The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Count Property is used to get the total number of the key/value pairs contained in the Hashtable. Syntax: myTable.Count Here, myTable is the name of the Hashtable.

2 min read

C# | Get or Set the value associated with specified key in Hashtable

Hashtable.Item[Object] Property is used to get or set the value associated with the specified key in the Hashtable. Syntax: public virtual object this[object key] { get; set; } Here, key is key of object type whose value is to get or set. Exceptions: ArgumentNullException: If the key is null. NotSupportedException: If the property is set and the Ha

3 min read

C# | Gets an ICollection containing the keys in the Hashtable

Hashtable.Keys Property is used to get an ICollection containing the keys in the Hashtable. Syntax: public virtual System.Collections.ICollection Keys { get; } Return Value: This property returns an ICollection containing the keys in the Hashtable. Note: The order of keys in the ICollection is unspecified. Retrieving the value of this property is a

2 min read

C# | Gets an ICollection containing the values in the Hashtable

Hashtable.Values Property is used to get an ICollection containing the values in the Hashtable. Syntax: public virtual System.Collections.ICollection Values { get; } Return Value: This property returns an ICollection containing the values in the Hashtable. Note: The order of values in the ICollection is unspecified. Retrieving the value of this pro

2 min read

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

C# | Adding an element into the Hashtable - GeeksforGeeks (2)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); jQuery('.suggest-bottom-btn').on('click', function(){ var suggest_val = $.trim($("#suggestion-section-textarea").val()); var error_msg = false; if(suggest_val != ""){ if(suggest_val.length <= 2000){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify({ "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

` }), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').html("Sent "); setTimeout(() => { jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); }, 1000); }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('#suggestion-modal-alert').html("Character limit exceeded."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('#suggestion-modal-alert').html("Enter valid input."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } }) $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

C# | Adding an element into the Hashtable - GeeksforGeeks (2024)

FAQs

C# | Adding an element into the Hashtable - GeeksforGeeks? ›

Add(Object, Object) Method is used to adds an element with the specified key and value into the Hashtable. Syntax: public virtual void Add(object key, object value);

How do you insert an element in a Hashtable? ›

To insert a new item in the table, we hash the key to determine which list the item goes on, and then insert the item at the beginning of the list. For example, to insert 11, we divide 11 by 8 giving a remainder of 3. Thus, 11 goes on the list starting at HashTable[3].

How do you access elements in a Hashtable? ›

Each element is assigned a key (converted key). By using that key you can access the element in O(1) time. Using the key, the algorithm (hash function) computes an index that suggests where an entry can be found or inserted.

How do you add items to a Hashtable? ›

And, you can add keys and values to a hashtable using the addition operator ( + ) to add a hashtable to an existing hashtable. For example, the following statement adds a Time key with a value of Now to the hashtable in the $hash variable. You can also add values that are stored in variables.

How does a Hashtable work internally in C#? ›

A HashTable collection stores a ( Key , Value ) pair and uses the Key to hash and obtain the storage location. The Key is immutable and cannot have duplicate entries in the HashTable .

How to add elements in a hashtable in C#? ›

The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable. Add(Object, Object) Method is used to adds an element with the specified key and value into the Hashtable.

Which method is used to add the data in a hashtable? ›

util. Hashtable. put() method of Hashtable is used to insert a mapping into a table. This means we can insert a specific key and the value it is mapping to into a particular table.

How are items found in a hash table? ›

A hash table uses a hash function to compute an index, also called a hash code, into an array of buckets or slots, from which the desired value can be found. During lookup, the key is hashed and the resulting hash indicates where the corresponding value is stored.

What is Hashtable in C# with example? ›

A Hashtable is a collection of key/value pairs that are arranged based on the hash code of the key. In other words, a Hashtable is used to create a collection that uses a hash table for storage.

Which is faster, Dictionary or Hashtable? ›

A Dictionary<TKey,TValue> of a specific type (other than Object) provides better performance than a Hashtable for value types. This is because the elements of Hashtable are of type Object; therefore, boxing and unboxing typically occur when you store or retrieve a value type.

Can a Hashtable have duplicate keys? ›

No , Hashtable do not accept duplicate keys. It stores key-value pairs in hash table data structure which internally maintains an array of list.

How do you insert an element in a HashMap? ›

put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.

What is the insertion order of a hashtable? ›

Hashtable does not maintains insertion order in java. LinkedHashMap maintains insertion order in java. TreeMap is sorted by natural order of keys in java. HashMap is not synchronized, hence its operations are faster as compared to Hashtable.

Top Articles
Latest Posts
Article information

Author: Nathanael Baumbach

Last Updated:

Views: 6079

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Nathanael Baumbach

Birthday: 1998-12-02

Address: Apt. 829 751 Glover View, West Orlando, IN 22436

Phone: +901025288581

Job: Internal IT Coordinator

Hobby: Gunsmithing, Motor sports, Flying, Skiing, Hooping, Lego building, Ice skating

Introduction: My name is Nathanael Baumbach, I am a fantastic, nice, victorious, brave, healthy, cute, glorious person who loves writing and wants to share my knowledge and understanding with you.