Best way to Query a Dictionary in C#
I have a dictionary, for example Dictionary<int, string>
.
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;
var stringValue = dictionary[key];
Can't you do something like:
var value = myDictionary[i];
?
string value = dictionary[key];
Dictionary.TryGetValue
is the safest way
or use Dictionary indexer as other suggested but remember to catch KeyNotFoundException
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]; }
}
}
精彩评论