Home > OS >  What is the syntax for saving a specific dictionary KeyValuePair to a variable?
What is the syntax for saving a specific dictionary KeyValuePair to a variable?

Time:03-19

I know that the syntax for iterating over a dictionary with foreach is:

foreach (KeyValuePair<key, value> item in dictionary)

Inside the foreach loop the key is accessed with item.key and the value with item.value.

What is the syntax for saving a KeyValuePair of a dictionary into a variable outside without the need of a foreach loop?

CodePudding user response:

Like this

    var dic = new Dictionary<string, int>();
    dic["a"] = 42;
    KeyValuePair<string, int> keyVal;
    foreach(var kv in dic) {
        keyVal = kv; << gets the last entry from the dictioanry
    }

Note that the dictionary does not store KeyValuePairs, it creates one for the enumeration, so the simple thing to do is this (because we are not expensively recreating something)

   var dic = new Dictionary<string, int>();
    dic["a"] = 42;
    KeyValuePair<string, int> keyVal = new KeyValuePair<string, int>("a", dic["a"]);

this is more efficient than the (neat) LINQ Sinlge method

CodePudding user response:

The IDictionary<TKey, TValue> interface implements IEnumerable<KeyValuePair<TKey,TValue>>. This means you can simply use Single() to get the entry you want.

IDictionary<string, int> dict = ...;
KeyValuePair<string, int> entry = dict.Single(it => it.Key == "yourKey");

CodePudding user response:

try this

var dict = new Dictionary<string, string>() {
    {"hi","Hello World!"},
    {"adieu","Goodby"}
    };
    

string hi = dict["hi"]; //Hello World!

or if you want a list

List<KeyValuePair<string,string>>  list = dict.ToList();

result

[{"Key":"hi","Value":"Hello World!"},{"Key":"adieu","Value":"Goodby"}]
  •  Tags:  
  • c#
  • Related