blah blah blah is here! blah blah » Close

up1down
link

is there a way to search a hashtable by value, not by key in c#?

last answered one year ago

1 answers

link

If you just want to check whether a particular value exists in the Hashtable, you can use the ContainsValue() method.

If you want to get the corresponding key (or keys) for a particular value, then the easiest way (if you're using .NET 3.5 or 4.0) is to use a LINQ query.

Here's a simple example:

using System;
using System.Collections;
using System.Linq;

class Test
{
static void Main()
{
Hashtable creatures = new Hashtable();
creatures.Add("lion", "mammal");
creatures.Add("spider", "insect");
creatures.Add("dog", "mammal");
creatures.Add("eagle", "bird");

if (creatures.ContainsValue("insect"))
{
Console.WriteLine("Creatures contains an insect");
}

// look for mammals

var query = from DictionaryEntry de in creatures where (string)de.Value == "mammal" select de;

foreach(DictionaryEntry de in query)
{
Console.WriteLine("{0} is a mammal", de.Key);
}

Console.ReadKey();
}
}

vulpes, you're the f'king man.

Feedback