简体   繁体   中英

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?

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是最安全的方法或使用Dictionary索引器作为其他建议,但记得抓住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]; }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM