Best way to Query a Dictionary in C# Best way to Query a Dictionary in C# asp.net asp.net

Best way to Query a Dictionary in C#


If you know the key is in the dictionary:

value = dictionary[key];

If you're not sure:

dictionary.TryGetValue(key, out value);


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.


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;