gpt4 book ai didi

c# - 如何在三个集合中进行 LINQ?

转载 作者:太空宇宙 更新时间:2023-11-03 23:12:21 24 4
gpt4 key购买 nike

我有三个集合:CandidateList、GroupList 和 PositionList。我想找出某个职位是否只有一个候选人,以及该特定组中是否有候选人担任该职位。是这样的:

candidateList = RetrieveCandidates();
groupList = RetrieveGroups();
positionList = RetrievePositions();

//first I loop through the candidates if there is at
//least 1 candidate per position, INCLUDING THE INDEPENDENT CANDIDATES.


foreach (var pos in positionList)
{
bool exists = candidateList.Any(x => x.PositionId == pos.PositionId)

if(!exists)
{
//throw exception
}

}

//then I loop through the groups if there is at least 1 candidate per position.
//This will make sure that all positions for each group has a member.

foreach (var grp in groupList)
{
foreach (var pos in positionList)
{
bool exists = candidateList.Any(x => x.PositionId == pos.PositionId && x.GroupId == grp.GroupId)

if(!exists)
{
//throw exception
}
}
}

有什么方法可以简化代码吗?最好是 LINQ

编辑:我忘了提及独立候选人 (candidate.CandidateId == 0)

最佳答案

您的第一张支票可以减少为:

var exists = positionList.All(p=> candidateList.Any(c=>c.PositionId == p.PositionId));

从那里我们可以创建您的第二张支票

exists = groups.All(
g =>positionList.All(
p=> candidateList.Any(
c=>c.PositionId == p.PositionId && c.GroupId == g.GroupId)));

关于c# - 如何在三个集合中进行 LINQ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38665076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com