Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query the value of an item`s property of a JArray with json.net [duplicate]

Tags:

c#

linq

json.net

My jsonarray has a serialized List of Products with Id and Name property.

JArray jsonarray  = JArray.Parse(json);

var name = // Get value for Name property which has Id 1.

How can I do this?

like image 658
Elisabeth Avatar asked Dec 20 '22 00:12

Elisabeth


1 Answers

You can try using linq:

JArray jsonarray = JArray.Parse("[{'Id':3, 'Name': 'Product3'}, {'Id':1, 'Name': 'Product1'}, {'Id':2, 'Name': 'Product2'}]");

var name = jsonarray
    .FirstOrDefault(x => x.Value<int>("Id") == 1)
    .Value<string>("Name");

Note that you should perform null check because FirstOrDefault may return null if an element with property Id == 1 is not found.

like image 197
Viktor Bahtev Avatar answered Dec 28 '22 22:12

Viktor Bahtev