Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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?

like image 790
Ka Marius Avatar asked Dec 18 '22 23:12

Ka Marius


2 Answers

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}]}]
like image 70
Gibbon Avatar answered Feb 20 '23 18:02

Gibbon


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 })});
like image 36
Jerodev Avatar answered Feb 20 '23 17:02

Jerodev