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

Advertisements

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:

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"; 

Leave a ReplyCancel reply