问题
What I'm trying to accomplish is to select the dateTimeStart inside the ttSheduleDay. The JSON beneath is a node of one employee, the function receives three parameters an empUID, a date and a value of (start / stop or duration).
The node I want to select is where the dsShedule > ttEmployee > empUID equals the first parameter, where the ttShedule > ttSheduleDay > dat equals the date parameter and the third parameter I will execute with an if statement. Below the JSON
JSON
{
"dsShedule": {
"ttEmployee": [
{
"empUID": 2649,
"empNameFirst": "firstname",
"empNameLast": "lastname",
"empFunction": "employee",
"ttShedule": [
{
"UID": 47,
"empUID": 2649,
"datStart": "2013-05-20",
"datStop": "2013-05-20",
"regime": 1,
"state": "PLANNED",
"ttSheduleDay": [
{
"SheduleUID": 47,
"dat": "2013-05-20",
"dateTimeStart": "2013-05-20T08:00:00.000",
"dateTimeStop": "2013-05-20T17:00:00.000",
"duration": 8
}
]
},
{
"UID": 57,
"empUID": 2649,
"datStart": "2013-05-21",
"datStop": "2013-05-21",
"regime": 1,
"state": "PLANNED",
"ttSheduleDay": [
{
"SheduleUID": 57,
"dat": "2013-05-21",
"dateTimeStart": "2013-05-21T08:00:00.000",
"dateTimeStop": "2013-05-21T17:00:00.000",
"duration": 8
}
]
}
]
},
The code I already have is to select the ttShedule
JObject jObj = JObject.Parse(json);
var linq = jObj["dsShedule"]["ttEmployee"]
// first filter for a single emp by empUID
.First(emp => emp["empUID"].Value<int>() == Convert.ToInt16(empUID))
.SelectToken("ttShedule");
The code suggested by someone on Stackoverflow was:
var linq = jObj["dsShedule"]["ttEmployee"]
// first filter for a single emp by empUID
.First(emp => emp["empUID"].Value<int>() == firstUID)
// then select the ttShedule array of that emp
.Select(emp => emp["ttShedule"])
// now filter for whatever ttShedule you need
.Where(shed => shed["ttSheduleDay"]
.Any(day => day["dat"].Value<DateTime>()
== new DateTime(2013, 5, 24))
But this failed on the select statement of ttShedule. I was wondering how i can expand my code to select the dateTimeStart node with the second if statement.
Thanks in advance
回答1:
Here's one way you could write your query:
var employeeId = 2649;
var date = new DateTime(2013, 5, 20);
var query =
from emp in jObj.SelectToken("dsShedule.ttEmployee")
where emp.Value<int>("empUID") == employeeId
let day =
(from sched in emp["ttShedule"]
from d in sched["ttSheduleDay"]
where d.Value<DateTime>("dat") == date
select d).FirstOrDefault()
where day != null
select day.Value<DateTime>("dateTimeStart");
I suspect the problem you were facing was that an employee with the specified id did not exist and the First()
call failed. This will not run into the same problem.
来源:https://stackoverflow.com/questions/16730454/complex-linq-nested-where-statements-json-net-and-linq