0

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

2
  • 1
    You can't deserialize that JSON to a dictionary, because it's a list of objects. Commented Jul 21, 2022 at 10:03
  • This is terrible code in general, I suggest a rewrite! Please accept OMANSAK's answer and I hope you getting paid bro. Commented Jul 21, 2022 at 10:57

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

I cant change anything in the code. I have to just use the Dictionary and model as it is and get the keys and values
.FirstOrDefault(a => a.Value.Value == "b").Key use this.
1

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.

Comments

0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.