[
{
"_id": "",
"at": IsoDate(2022-11-19 10:00:00),
"areaId": 3,
"data": [
{
"label": 1,
"name": "a",
"sec": 34,
"x": 10.3,
"y": 23.3
},
{
"label": 1,
"name": "a",
"sec": 36,
"x": 10.3,
"y": 23.3
}
]
},
{
"_id": "",
"at": IsoDate(2022-11-19 10:01:00),
"areaId": 4,
"data": [
{
"name": "a",
"label": 1,
"sec": 10,
"x": 10.3,
"y": 23.3
},
{
"label": 2,
"name": "b",
"sec": 12,
"x": 10.3,
"y": 23.3
}
]
}
]
I have a data like above and I want to get the data of only objects with label=1 from this data with the help of linq.
In other words, 2 data should come from the data field of the areaId=3 object and 1 data from the field of the areaId=4 object.
The return type will be the same.
How can I do this with LINQ?
CodePudding user response:
// assuming your an array is filled with your JSON data.
var array = ... // the array
var filtered = array
.SelectMany(a => a.Data)
.Where(d => d.Label == 1);
With this code you will get only 3 data results 2 from the first and 1 from the second.
var array = ... // the array
// Only get base object (with areaId) containing at least 1 data with label = 1
var filtered = array
.Where(a => a.Data.Any(d => d.Label == 1));
foreach(var item in filtered)
{
foreach(var data in item.Data.Where(d => d.Label == 1))
{
var areaId = item.AreaId;
var name = data.name;
// ...
}
}
CodePudding user response:
var array...
array = array
.Select(arrayItem => new YourReturnType
{
AreaId = arrayItem.areaId,
At = arrayItem.At,
Data = arrayItem.Data.Where(dataItem => dataItem.Label == 1)
});
The "YourReturnType" is the parent, I don't know whats the name in your code.