如何在三个集合中LINQ

本文关键字:三个 集合 LINQ | 更新日期: 2023-09-27 17:59:11

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

编辑:我忘了提到独立候选人(候选人.CandidatedId==0)

如何在三个集合中LINQ

您的第一次检查可以简化为:

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)));
candidateList.Where(c=>positionList.Any(pos=>pos.PositionId == c.PositionId) 
        && groupList.Any(g=>g.GroupId == c.GroupId))

将从这两个列表中筛选至少有一个职位和一组的候选人。

如果第二条语句为真,则不需要第一条语句,如果每个组至少有一名候选人有职位,则至少有一位候选人有职位

positionList.All(pos=>
        groupList.All(grp=>
           canidateList.Any(can=> can.PositionId==pos.PositionId 
                                  && can.GroupId == grp.GroupId))); 

然而,请注意,您也在为两种不同的情况做例外处理,这样您就可以创建一个匿名对象来选择没有匹配项的组,并检查候选项

var result = 
    positionList.Select(pos=>new { 
        Position = pos,
        DoesNotHaveOneCanidate = 
            !canidateList.Any(can=> can.PositionId==pos.PositionId), 
        GroupsMissing = 
            groupList.Where(grp=>
                !canidateList.Any(can=> can.PositionId==pos.PositionId 
                                     && can.GroupId == grp.GroupId)
           ) 
    });