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

标签 c# linq

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

相关文章:

c# - C# .NET 中部分文档的 Xml 签名验证失败

c# - 在 Mongo Linq 查询中执行相交的机制是什么

c# - 将传感器数据对象转换为字节数组 (C#)

c# - 如何使用 C# 连接到 Winform 应用程序中的 .sdf 文件?

c# - 使用星号显示和揭开字母

c# - 按属性的反射顺序

c# - LINQ 中的动态变量

c# - 在 EF Core 中更新数据的更好方法是什么

c# - 如何在 Linq to SQL 中确定记录是否已成功添加?

linq - 学习 LinqToSql 还是坚持使用 ADO.NET?