How to Select only Id's with linq when there is List in List

  • A+
Category:Languages

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}]}] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: