You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用LINQ的Select/SelectMany提取嵌套列表中的ID

Solution: Extract Only IDs with LINQ Select

Got it, let's adjust your code to pull just the IDs instead of full employee objects. Here's how to do it with nested Select calls:

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

What's changed?

  • Instead of assigning p.Employees directly (which returns full employee objects), we use p.Employees.Select(e => e.Id) to project each employee to their ID only.
  • This keeps your data grouped by office, giving you an anonymous type with each office's ID and a list of corresponding employee IDs.

If you want a flat list instead (no grouping by office):

If your goal is a single list of (Office ID + Employee ID) pairs rather than grouped collections, use SelectMany to flatten the nested structure:

var flatEmployeeOfficePairs = offices.SelectMany(p => 
    p.Employees.Select(e => new {
        OfficeId = p.Id,
        EmployeeId = e.Id
    })
).ToList();

SelectMany works here by iterating over each office, then each employee in that office, and combining them into a single list of the anonymous type with both IDs.

内容的提问来源于stack exchange,提问作者Marius Kazlauskas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:04:54