如何在C#中为JSON对象中的列表值化一个条件。

问题描述 投票:0回答:2

我有一个JSON文件,我必须基于一个JSON元素来执行数据验证。

以下是我的json文件

[
  {
    "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"
  }
]

以下是代码片段

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

在这里,我希望displayname的值是基于通过的if条件。所以,在我的if循环中,如果把list.displayname的值打印出来,我需要的是 周六夜现场

c# .net json .net-framework-version jsonserializer
2个回答
1
投票
// 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;

0
投票

检查这个。

var name = list.Where(e=>e.id=="3718").Select(x=>x.displayName);
© www.soinside.com 2019 - 2024. All rights reserved.