Reputation: 2393
I have objects in hashtable, in that object I have a list, how to access it?
ls.cs
class lh
{
public string name;
public List<ulong> nList = new List<ulong>();
public lh(string name)
{
this.name = name; ;
}
}
Program.cs
static void Main(string[] args)
{
while((line=ps.ReadLine()) != null)
{
gen.h_lh.Add(line, new lh(line));
}
}
public class gen
{
public static Hashtable h_lh = new Hashtable();
}
this works. when I debug I can see the object created in the hashtable; I just cant/dont know how to access/store value to the list it's gotta be something like gen.h_lh[lh].something right ? but this didnt work. what did I miss?
Upvotes: 0
Views: 273
Reputation: 499
foreach(System.System.Collections.DictionaryEntry entry in h_lh)
{
Console.WriteLine("Key: " + entry.Key.ToString() + " | " + "Value: " + entry.Value.ToString());
}
or you could access it using a key
lh myLh = h_lh[line];
Update answer for comment
foreach(System.System.Collections.DictionaryEntry entry in h_lh)
{
List<ulong> nList = (ulong)entry.Value;
nList.Add(1);
}
Upvotes: 0
Reputation: 1877
A hash tables is a data structure that represents a set. That means that by definition, you don't want to access the hash table to get an element, you just want to add, remove, or aks if an element exists. These are the basic operations with sets.
This said, HashSet<T>
in .NET has no indexer. Why? Consider the line that you wrote yourself:
var item = gen.h_lh[lh]
If you really can provide the lh
to index, what do you expect the hash table to give you? The same instance? Of course not, you already have it, if you are using it in the indexer. So perhaps your problem it's not very well determined.
First of all you need to determine why (and how) you want to access the elements. All you want is to iterate through all of them, or you want to quickly index any one of them? If you just want to get all the elements at some point, then you have all you need: HashSet<T>
implements IEnumerable<T>
. If you need to get an specific element, then you must have some key to identify the element (like the name
property here), and in this case what you want is not a HashSet<lh>
but a Dictionary<string,lh>
, just like @Tergiver said.
Upvotes: 0
Reputation: 14517
First of all Hashtable
is obsolete, use Dictionary<TKey, TValue>
instead (Dictionary<string, lh>
in your case).
Given a key, you can access the value of that key with: h_lh[key]
.
Or you can enumerate all of the key/value pairs with:
foreach (KeyValuePair<string, lh> pair in h_lh)
pair.Value // this is an lh object
You can also enumerate just keys h_lh.Keys
, or just values h_lh.Values
.
Upvotes: 1