Reputation: 79
I have a JSON file, where i have to perform a data validation based on a json element.
below is my json file
[
{
"id": "5241585099662481339",
"displayName": "Music",
"name": "music",
"slug": "music",
"imageUrl": "http://mno.com"
},
{
"id": "6953585193220490118",
"displayName": "Celebrities",
"name": "celebrities",
"slug": "celebrities",
"imageUrl": "http://ijk.com"
},
{
"id": "5757029936226020304",
"displayName": "Entertainment",
"name": "entertainment",
"slug": "entertainment",
"imageUrl": "http://pqr.com"
},
{
"id": "3718",
"displayName": "Saturday Night Live",
"name": "saturday night live",
"slug": "saturday-night-live",
"imageUrl": "http://efg.com"
},
{
"id": "8113008320053776960",
"displayName": "Hollywood",
"name": "hollywood",
"slug": "hollywood",
"imageUrl": "http://qwe.com"
}
]
Below is code snippet
var list = JsonConvert.DeserializeObject<List<MyItem>>(json);
if (list.Any(e => e.id =="3718"))
{
//How do get the exact displayName on the if condtion
}
public class MyItem
{
public string id;
public string displayName;
public string name;
public string slug;
public string imageUrl;
}
Here i want the displayname value based on the if condtion passed. So inside my if loop if put list.displayname i need the value to printed as Saturday Night Live
Upvotes: 0
Views: 52
Reputation: 45
Check this:
var name = list.Where(e=>e.id=="3718").Select(x=>x.displayName);
Upvotes: -1
Reputation: 93
// name will be null if there isn't any item where id == 3718
var name = list.FirstOrDefault(item => string.Equals(item.id, "3718"))?.displayName;
// InvalidOperationException will be thrown if there isn't any item where id == 3718
var name = list.First(item => string.Equals(item.id, "3718")).displayName;
Upvotes: 2