Skip to main content
 首页 » 编程设计

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

2024年04月18日33mq0036

我有三个集合: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)));