I want to select only id's from List of objects in another List: https://dotnetfiddle.net/Leu1AD
I need to use only linq Select or SelectMany:
var obj = offices.Select(p => new {Id = p.Id, Employess = p.Employess}).ToList();
Currently I get following result:
[
{
"Id":1,
"Employess":[
{
"Id":1,
"FirstName":"a",
"LastName":"b"
},
{
"Id":2,
"FirstName":"c",
"LastName":"d"
}
]
},
{
"Id":2,
"Employess":[
{
"Id":3,
"FirstName":"e",
"LastName":"f"
},
{
"Id":4,
"FirstName":"g",
"LastName":"h"
}
]
}
]
But I need this result:
[
{
"Id":1,
"Employess":[
{
"Id":1
},
{
"Id":2
}
]
},
{
"Id":2,
"Employess":[
{
"Id":3
},
{
"Id":4
}
]
}
]
Do you have any ideas how to do that?
One method to get the result to be the format you want is along the lines of
var obj = offices.Select(p => new {Id = p.Id, Employess = p.Employess.Select(y=> new {y.Id})}).ToList();
ends up as
[{"Id":1,"Employess":[{"Id":1},{"Id":2}]},{"Id":2,"Employess":[{"Id":3},{"Id":4}]}]
You need a second Select
that only selects the Employee Id
.
var obj = offices.Select(o => new {Id = o.Id, Employess = o.Employess.Select(e => new { Id = e.Id })});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With