简体   繁体   English

如果列表中有List,如何仅使用linq选择Id

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

I want to select only id's from List of objects in another List: https://dotnetfiddle.net/Leu1AD 我想从另一个列表中的对象列表中仅选择id: https//dotnetfiddle.net/Leu1AD

I need to use only linq Select or SelectMany: 我只需要使用linq Select或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}]}]

您需要第二个Select仅选择员工Id

var obj = offices.Select(o => new {Id = o.Id, Employess = o.Employess.Select(e => new { Id = e.Id })});

alter your line 改变你的路线

var obj = offices.Select(p => new {Id = p.Id, Employess = p.Employess}).ToList();

to

var obj = offices.Select(p => new {Id = p.Id, Employess = p.Employess.Select(x=>new{Id=x.Id})}).ToList();

To have the expected result just replace: 要获得预期结果,只需替换:

Employess = p.Employess

With

Employess = p.Employess.Select(e => new { e.Id })

Finally you have this LINQ statement: 最后你有这个LINQ语句:

var obj = offices.Select(p => new {Id = p.Id, Employess = p.Employess.Select(e => new { e.Id })}).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM