使用linq检查是否不存在子句

本文关键字:不存在 子句 是否 检查 linq 使用 | 更新日期: 2023-09-27 18:20:25

以下是我一直试图解决的情况

让我们拿一张员工表

Create Table Employee
(
        Employeeid int primary key,
        EMPname varchar(50),
        ManagerEmplId int reference key Employee (EmployeeID)
         TreeLevel int,
              ....
)

在这里我需要找到所有叶子级别的员工。

叶级员工-所有有经理但没有任何人向其报告的员工。我从db那里得到了一些帮助,它有TreeLevel列,我可以在其中指定pick级别为3的任何人,但我需要一个UNION子句,它可以让我获得树级别为2的所有没有任何员工报告的员工。如果这有助于创建linq查询,那么我只有三级树。

   return ((from b in _db.Employees
                && b.TreeLevel==3 && b.DeletedDate== null
                    select b)
                    .Union
                    (from b in _db.Employees
                     select b)
                    )
                    .ToDictionary(k => k.EmployeeID, v => v.EMPname);

更新:真正的问题:

(from fi in firm 
 join bra in _db.Branches on fi.BranchID equals bra.ParentBranchID into g 
 from sc in g.DefaultIfEmpty() 
 where fi.DeletedDate == null && g == null 
 select fi)
 .ToList()
 .ToDictionary(k => k.BranchID, v => v.BranchName);

错误:

Cannot compare elements of type 'System.Collections.Generic.IEnumerable`1'. 
Only primitive types (such as Int32, String, and Guid) and entity types are supported.

使用linq检查是否不存在子句

您可以尝试右外连接,并确保左侧为空。

在这篇文章中,如何在Linq中进行完整的外部联接?你可以在linq找到一个如何做到这一点的好例子。

from b in _db.Employees
from c in _db.Employees.Where(o=> o.ManagerEmplId == b.Id).DefaultIfEmpty()
where c == null

不管树的深度如何,这个查询都应该完成任务:

var leafEmps = 
    (from emp in _db.Employees
     where !_db.Employees.Any(e => e.ManagerEmplId == emp.EmployeeId)
     select emp);
var managersids = _db.Employees.Select(emp => emp.ManagerEmplId ).Distinct();
var leafemps = _db.Employees.where(emp => !managersids.contains(emp.Employeeid));

要做到这一点很简单,找到所有的经理,然后搜索没有经理的人

var leafemps = from emp in _db.Employees
               let managersids = _db.Employees.Select(emp => emp.ManagerEmplId ).Distinct()
               where !managersids.contains(emp.Employeeid)
               select emp