Compare values from objects stored in Hashtable

F

Frank

Hi!

I'm kinda stuck here.
I have an Hashtable with with my custom "Item" Object. The key used in
the Hashtable is the "Item.Id", i have selected this key because with
a lot of functions i can get the right object from the hashtable
really fast. But now i need a function whom can get an object from the
hashtable based on the values each "Item" object holds.
("Item.ColorId","Item.SizeId","Item.OtherId"), but i can't identify
the object by its key (the "Item.Id").

Since it is an hashtable i can't loop through each instance and then
cast and compare the values like you could do with an arraylist. Has
someone got an idea ?

Best Regards,
Frank
 
L

Liam McNamara

When you say you can't loop through the Hashtable do you mean because of how
inefficient a linear search is? It is possible to iterate through it:

foreach(Item anItem in myHashtable)
{
if(anItem.ColorId == someColor)
...
}

--Liam.
 
D

David Anton

No, you usually can't iterate through each object in a Hashtable that
way, since it contains objects, not specific types (you'll throw
exceptions left and right if you try).

Instead:
foreach (string sKey in myHashtable.Keys)
{
if(myHashtable[sKey].ColorId == someColor)
...
}

*-----------------------*
Posted at:
www.GroupSrv.com
*-----------------------*
 
D

David Anton

Ack - that's not quite right either - you need to cast to an "Item"
object.

This is what you need:

foreach (string sKey in myHashtable.Keys)
{
if (((Item)myHashtable[sKey]).ColorId == someColor)
...
}

*-----------------------*
Posted at:
www.GroupSrv.com
*-----------------------*
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top