Ananth
Ananth

Reputation: 10700

Best way to Query a Dictionary in C#

I have a dictionary, for example Dictionary<int, string>.
What would be the best way to get the string value if I know the key?

Upvotes: 9

Views: 21044

Answers (8)

Scott
Scott

Reputation: 13931

If you want to query against a Dictionary collection, you can do the following:

static class TestDictionary 
{
    static void Main() {
        Dictionary<int, string> numbers;
        numbers = new Dictionary<int, string>();
        numbers.Add(0, "zero");
        numbers.Add(1, "one");
        numbers.Add(2, "two");
        numbers.Add(3, "three");
        numbers.Add(4, "four");

        var query =
          from n in numbers
          where (n.Value.StartsWith("t"))
          select n.Value;
    }
}

You can also use the n.Key property like so

var evenNumbers =
      from n in numbers
      where (n.Key % 2) == 0
      select n.Value;

Upvotes: 6

Oded
Oded

Reputation: 499002

What do you mean by best?

This is the standard way to access Dictionary values by key:

var theValue = myDict[key];

If the key does not exist, this will throw an exception, so you may want to see if they key exists before getting it (not thread safe):

if(myDict.ContainsKey(key))
{
   var theValue = myDict[key];
}

Or, you can use myDict.TryGetValue, though this required the use of an out parameter in order to get the value.

Upvotes: 10

Michiel Peeters
Michiel Peeters

Reputation: 400

Well I'm not quite sure what you are asking here but i guess it's about a Dictionary?

It is quite easy to get the string value if you know the key.

string myValue = myDictionary[yourKey];

If you want to make use like an indexer (if this dictionary is in a class) you can use the following code.

public class MyClass
{
  private Dictionary<string, string> myDictionary;

  public string this[string key]
  {
    get { return myDictionary[key]; }
  }
}

Upvotes: 2

to StackOverflow
to StackOverflow

Reputation: 124696

If you know the key is in the dictionary:

value = dictionary[key];

If you're not sure:

dictionary.TryGetValue(key, out value);

Upvotes: 21

Captain Comic
Captain Comic

Reputation: 16196

Dictionary.TryGetValue is the safest way or use Dictionary indexer as other suggested but remember to catch KeyNotFoundException

Upvotes: 2

Diego Mijelshon
Diego Mijelshon

Reputation: 52725

string value = dictionary[key];

Upvotes: 3

zerkms
zerkms

Reputation: 254916

var stringValue = dictionary[key];

Upvotes: 4

delete
delete

Reputation:

Can't you do something like:

var value = myDictionary[i];?

Upvotes: 3

Related Questions