hashtable in asp.net
1.I want to display each record of hashtable in label but 开发者_JS百科i am unable to apply for each loop in hash table.
2.why we use hashtable instead of data table.int key;
string name = string.Empty;
string str = string.Empty;
Hashtable hashtable = new Hashtable();
key = 1;
name = "A";
hashtable.Add(key,name);
key = 2;
name = "B";
hashtable.Add(key,name);
key = 3;
name = "lily";
hashtable.Add(key,name);
Re 2: with .NET 2.0 and above there is indeed little point in using Hashtable
here unless you have a specific reason (such a the lock-semantics). However, DataTable
is even less desirable (IMO). The better replacement would be Dictionary<int,string>
- or if the keys are always 1,2,3,... maybe just a string[]
and offset by one.
With a dictionary you get a KeyValuePair<TKey,TValue>
in foreach, I.e.
foreach(var pair in data) {
int key = pair.Key;
string value = pair.Value;
//...
}
1) i am unable to apply for each loop in hash table
foreach (string key in hashtable.Keys) {
Response.Write(key + '=' + hashtable[key] + "<br>");
}
2) why we use hashtable instead of data table.
Searching withing a hashtable is faster.
Use a hash table if searching is a priority. Hash tables provide very quick search mechanisms when searching by key, and fairly good searching when searching by value
Use a hash table if you want to be able to remove specific elements (use the Remove method)
Use a hash table when the order the elements is stored is irrelevant to you
Don't use a hash table if you need the elements in some specific order. You cannot rely on how a Hashtable will sort its elements
Don't use a hash table if you need to insert an element in a particular location
Don't use a hash table if you want to store multiple keys with the same value. All keys inside a hash table must be unique
[reference]
If you want to iterate over it, you can iterate over just the values:
foreach(var value in hashtable.Values)
{
}
As to why use Hashtable rather than DataTable, DataTable is rather richer in terms of functionality and heavier in terms of memory and processing overhead.
However, I would argue that since Hashtable is not strongly typed, it's more usual to use a generic collection, such as Dictionary these days.
精彩评论