Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get a specific value from IList<IDictionary<string, string>> based on a string that needs to match the key of that value

I have

IList<IDictionary<string,string>>

and Im trying to get a value of the list of dictionaries based on a string which needs to match the key.

For example if we have:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

IList<IDictionary<string, string>> listOfDicts = new IList 
{
    new IDictionary<string, string>
    {
        {"key1", "value1"},
        {"key2", "value2"},
        {"key3", "value3"}
    }
};

How can I get "value2" based on a userInput string which is "key2" for this example, I need to match the key to the input and get the value?

>Solution :

Since you declared List, you have several dictionaries, e.g.

IList<IDictionary<string, string>> listOfDicts = 
  new List<IDictionary<string, string>>() {
    new Dictionary<string, string>() {
      { "key1", "value1" },
      { "key2", "value2" },
    },

    new Dictionary<string, string>() {
      { "key1", "OtherValue1" },
      { "key3", "OtherValue3" },
      { "key4", "OtherValue4" },
    },
  };

To obtain all values ("value1", "OtherValue1"):

using System.Linq;

...

string key = "key1";

var values = listOfDicts
  .Where(dict => dict.ContainsKey(key))
  .Select(dict => dict[key])
  .ToArray(); // let's have an array of values

To obtain first value ("value1") only:

string key = "key1";

string value = listOfDicts
  .FirstOrDefault(dict => dict.ContainsKey(key))
  ?[key] ?? "DefaultValue"; 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading