我想从另一个List中的对象列表中仅选择id: https://dotnetfiddle.net/Leu1AD
我只需要使用linq Select或SelectMany:
[
{
"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"
}
]
}
]
目前我得到以下结果:
[
{
"Id":1,
"Employess":[
{
"Id":1
},
{
"Id":2
}
]
},
{
"Id":2,
"Employess":[
{
"Id":3
},
{
"Id":4
}
]
}
]
但我需要这个结果:
import {provideRouter, RouterConfig} from '@angular/router';
import { AdminpanelComponent } from './components/adminpanel/adminpanel.component';
import { LoginComponent } from './components/login/login.component';
export const AppRoutes: any = [
{ path: '', component: 'LoginComponent'},
{ path: 'login', component: LoginComponent },
{ path: 'admin', component: AdminpanelComponent },
{ path: '**', component: LoginComponent }
];
export const AppComponents: any = [
LoginComponent,
AdminpanelComponent
];
你有什么想法怎么做?
答案 0 :(得分:6)
将结果作为所需格式的一种方法是
var obj = offices.Select(p => new {Id = p.Id, Employess = p.Employess.Select(y=> new {y.Id})}).ToList();
结束为
[{"Id":1,"Employess":[{"Id":1},{"Id":2}]},{"Id":2,"Employess":[{"Id":3},{"Id":4}]}]
答案 1 :(得分:2)
您需要第二个Select
仅选择员工Id
。
var obj = offices.Select(o => new {Id = o.Id, Employess = o.Employess.Select(e => new { Id = e.Id })});
答案 2 :(得分:2)
改变你的行
var obj = offices.Select(p => new {Id = p.Id, Employess = p.Employess}).ToList();
到
var obj = offices.Select(p => new {Id = p.Id, Employess = p.Employess.Select(x=>new{Id=x.Id})}).ToList();
答案 3 :(得分:1)
要取代预期结果:
Employess = p.Employess
使用
Employess = p.Employess.Select(e => new { e.Id })
最后你有这个LINQ语句:
var obj = offices.Select(p => new {Id = p.Id, Employess = p.Employess.Select(e => new { e.Id })}).ToList();