Home > OS >  How to get the key and value from dictionary
How to get the key and value from dictionary

Time:07-21

I have dictionary like this :

"parameters": [
        {
            "name": "a",
            "value": "b"
        },
        {
            "name": "c",
            "value": "d"
        }
    ],

Have defined the dictionary like this :

Dictionary<string, atypeModel>

where atypeModel is like this :

 public class atypeModel
    {
        public string Name { get; set; }

        public string Value { get; set; }
    }

now , what Im not getting is how to retrieve the value by key . I did below :

var myKey = types.FirstOrDefault(a => a.Value == "b").Key;

but it is giving below error :

Operator '==' cannot be applied to operands of type 'atypeModel' and 'string '

please suggest

CodePudding user response:

try var myKey = types.FirstOrDefault(a => a.Value.Value == "b").Key;

your dictonary like as :

[
  {
    "name": "a",
    "value": {
      "Name": "a",
      "Value": "b"
    }
  }
]

If you want this

[
  {
    "name": "a",
    "value": "b"
  },
  {
    "name": "c",
    "value": "d"
  }
]

you should make List<atypeModel>

CodePudding user response:

The word "Value" is used by "Dictionary" and also your class "atypeModel". It may be a little confuse to use both "properties". I sugest you change your class "Value" property for "TypeValue" and then:

(...).FirstOrDefault(a => a.Value.TypeValue == "b").Key

...just like OMANSAK said on comments.

CodePudding user response:

You can not deserialize above json into the form of Dictionary<string, atypeModel>. You need List in the value, because value of "parameters" is of type List.

First change your model to Dictionary<string, List<atypeModel>>.

Now once you change your model, now things are easy, just apply same logic on the types["parameters"]

Like,

Dictionary<string, List<atypeModel>> types = JsonConvert.DeserializeObject<Dictionary<string, List<atypeModel>>(json)
var myKey = types["parameters"].FirstOrDefault(a => a.Value == "b").Key;
           //^^^^^^^^^^^^^^ This was missing
  •  Tags:  
  • c#
  • Related