Reputation: 602
I'm trying to select the node where empUID equals a certain ID. Here is my JSON snippet
{
"dsShedule": {
"ttEmployee": [
{
"empUID": 2649,
"empNameFirst": "Firstname",
"empNameLast": "lastName",
"empFunction": "AFWERKER DRUKKERIJ",
"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
}
]
}
]
},
I'm able to select all the employee nodes but the moment I try to select the node where the ID equals for example 494323, it can not be found.
JObject jObj = JObject.Parse(json);
int firstUID = 494323;
var linq = jObj["dsShedule"]["ttEmployee"].Select(x => new
{
empUID = x.SelectToken("empUID"),
empNameFirst = x.SelectToken("empNameFirst"),
empNameLast = x.SelectToken("empNameLast"),
ttShedule = x.SelectToken("ttShedule")
});
var uid = linq.Where(x => x.empUID.Equals(firstUID));
I'm using VS2012 and when I debug the element linq and look for the value of empUID, it shows the value {494323} (Why the brackets?).
Below a picture of the variables:
As you can see uid is empty, what am I missing?
Thanks in advance
Upvotes: 2
Views: 2513
Reputation: 16042
You select not the values in your select query but JToken objects:
empUID = x.SelectToken("empUID")
empUID is of type JToken (you can see the type in the debug view). Then you try to compare an integer to a JToken which will fail.
Just select the values like this:
empUID = x.SelectToken("empUID").Value<int>()
Or use Value<T>
when comparing:
var uid = linq.Where(x => x.empUID.Value<int>() == firstUID);
EDIT
Im not sure what you exactly want, but this should give you an idea.
Filter with Where
all ttSchedule entries, that contain a ttSheduleDay with a dat property of a given value:
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))
Upvotes: 3