I am having a JSON object (NewtonSoft.JObject). It contains several entries in this format:
我有一个JSON对象(NewtonSoft.JObject)。它包含以下格式的几个条目:
{
"id": "b65ngx59-2c67-4f5b-9705-8525d65e1b8",
"name": "TestSample",
"versions": []
},
{
"id": "8acd8343-617f-4354-9b29-87a251d2f3e7",
"name": "template 2",
"versions": [
{
"id": "556ng956-57e1-47d8-9801-9789d47th5a5",
"template_id": "8acd8343-617f-4354-9b29-87a251d2f3e7",
"active": 1,
"name": "1.0",
"subject": "<%subject%>",
"updated_at": "2015-07-24 08:32:58"
}
]
}
Note: Just an example.
注意:只是一个例子。
I have written a code so that I get the ids in a list:
我编写了一个代码,以便在列表中获取ID:
List<JToken> templateIdList = jObj.Descendants()
.Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "id")
.Select(p => ((JProperty)p).Value)
.ToList();
Note: jObj is the JSON object
注意:jObj是JSON对象
The output list is:
输出列表是:
[0] - b65ngx59-2c67-4f5b-9705-8525d65e1b8
[1] - 8acd8343-617f-4354-9b29-87a251d2f3e7
[2] - 556ng956-57e1-47d8-9801-9789d47th5a5
It gives all the ids.Now I want to add a condition to the linq so that only the template_ids containing active with value = 1 in them should be populated in the list.
它给出了所有的ID。现在我想为linq添加一个条件,这样只应在列表中填充包含value = 1的active_ids的template_ids。
The required output:
所需的输出:
[0] - 8acd8343-617f-4354-9b29-87a251d2f3e7
What changes should I make to the linq query to get this?
我应该对linq查询进行哪些更改才能获得此信息?
EDIT: The complete code is
编辑:完整的代码是
public bool CheckIfTemplateExists(string template)
{
bool exists = false;
//web service call to retrieve jsonTemplates
JObject jObj = JObject.Parse(jsonTemplates);
List<JToken> templateIdList = jObj.Descendants()
.Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "id")
.Select(p => ((JProperty)p).Value)
.ToList();
if(templateIdList.IndexOf(template) != -1)
{
exists = true;
}
return exists
}
The jsonTemplates in the above code is a string of the format:
上面代码中的jsonTemplates是一个格式的字符串:
{"templates":
[{"id":"b65cae59-2c67-4f5b-9705-07465d65e1b8",
"name":"TestSample","versions":[]},
{"id":"8edb8343-617f-4354-9b29-87a251d2f3e7",
"name":"Template1",
"versions":[{"id":"556bb956-57e1-47d8-9801-9388d47cc5a5",
"template_id":"8edb8343-617f-4354-9b29-87a251d2f3e7",
"active":1,
"name":"1.0","subject":"\u003c%subject%\u003e",
"updated_at":"2015-07-24 08:32:58"}]}
1 个解决方案
#1
5
Try this one:
试试这个:
List<JToken> templateIdList = jObj["templates"].Children()
.Where(child => child["versions"] != null
&& child["versions"].Any(version => version["active"].Value<int>() == 1))
.Select(x => x["id"]);
#1
5
Try this one:
试试这个:
List<JToken> templateIdList = jObj["templates"].Children()
.Where(child => child["versions"] != null
&& child["versions"].Any(version => version["active"].Value<int>() == 1))
.Select(x => x["id"]);