采用以下示例:
public class Team
{
public int Id { get; set; }
public string TeamName { get; set; }
public Members[] Members { get; set; }
}
public class Members
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
如果我有由以下人员组成的C#团队名单:
[
{
"Id" : 1,
"TeamName" : "A",
"Members": [
{
"Id": 1,
"FirstName": "Arthur",
"LastName": "Nudge"
},
{
"Id": 2,
"FirstName": "Ken",
"LastName": "Shabby"
}
]
},
{
"Id" : 2,
"TeamName" : "B",
"Members": [
{
"Id": 1,
"FirstName": "Spiny",
"LastName": "Norman"
},
{
"Id": 2,
"FirstName": "Raymond",
"LastName": "Luxury-Yacht"
}
]
}
]
我该如何通过成员以及团队ID等方式对Linq查询进行giva
{
"TeamId": 1,
"Id": 1,
"FirstName": "Arthur",
"LastName": "Nudge"
},
{
"TeamId": 1,
"Id": 2,
"FirstName": "Ken",
"LastName": "Shabby"
},
{
"TeamId": 2,
"Id": 1,
"FirstName": "Spiny",
"LastName": "Norman"
}
我可以使用以下方法从“团队”列表中返回“成员”列表
Teams.SelectMany(t => t.Members).ToList();
,但如何同时包含TeamId
答案 0 :(得分:3)
以这种方式使用SelectMany
:
var q = Teams
.SelectMany(t => t.Members
.Select(tm => new{ TeamId = t.Id, tm.Id, tm.FirstName, tm.LastName }));
答案 1 :(得分:1)
您可以使用自定义LINQ查询将其组合为带有所需字段的匿名对象列表:
var list = (from team in Teams
from member in team.Members
select new
{
TeamId = team.Id,
member.Id,
member.FirstName,
member.LastName
}).ToList();
答案 2 :(得分:0)
结合使用SelectMany
和Select
:
teams.SelectMany(team => team.Members.Select(member => new
{
TeamId = team.Id,
MemberId = member.Id,
member.FirstName,
member.LastName
})).ToList();
Select
将每个成员和团队ID映射为匿名类型。SelectMany
将嵌套的IEnumerable<...>
展平为单个IEnumerable<...>