如何使用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.Employeesdirectly (which returns full employee objects), we usep.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
相关产品推荐
相关产品推荐

