我正在尝试编写等同于:
的LINQ语句select e.EmployeeID, EmployeeName = e.FirstName + ' ' + e.LastName
from Employees e
where e.EmployeeID not in
(
select EmployeeID from Managers
)
我认为我与以下内容非常接近:
from e in Employees
where e.EmployeeID != // This is where I'm lost
(
from m in Managers select m.EmployeeID
)
select new
{
e.EmployeeID,
EmployeeName = e.FirstName + ' ' + e.LastName
}
我正在尝试将其放入Html.DropDownList。
答案 0 :(得分:7)
我不确定对此的正确查询符号是什么,但以下扩展语法将完成工作
var result = Employees
.Where( e => !Managers.Where(m => m.EmployeeId == e.EmployeeId).Any())
.Select( e => new { EmployeeId = e.EmployeeId, EmployeeName = e.FirstName + ' ' + e.LastName);
答案 1 :(得分:4)
使用Any
:
from e in Employees
where !Managers.Any(m => m.EmployeeID == e.EmployeeID)
select new
{
e.EmployeeID,
EmployeeName = e.FirstName + ' ' + e.LastName
}
或者,使用左连接:
from e in Employees
join m in Managers on e.EmployeeID equals m.EmployeeID into managerGroup
from m in managerGroup.DefaultIfEmpty()
where m == null
select new
{
e.EmployeeID,
EmployeeName = e.FirstName + ' ' + e.LastName
}
答案 2 :(得分:3)
您可以使用fluid implementation of Linq.Except():
获得所需的结果List<Employee> employees = new List<Employee>
{
new Employee { EmployeeID = 1, FirstName = "John", LastName = "Smith" },
new Employee { EmployeeID = 2, FirstName = "Jane", LastName = "Doe" },
new Employee { EmployeeID = 3, FirstName = "Eddie", LastName = "Punchclock" }
};
List<Employee> managers = new List<Employee>
{
new Employee { EmployeeID = 2, FirstName = "Jane", LastName = "Doe" },
};
var nonManagerEmployees = employees.Except(managers, x => x.EmployeeID)
.Select(x => new
{
x.EmployeeID,
EmployeeName = x.FirstName + " " + x.LastName
});
foreach(var entry in nonManagerEmployees)
{
Console.WriteLine(entry.EmployeeID+" "+entry.EmployeeName);
}
输出:
1 John Smith
3 Eddie Punchclock
答案 3 :(得分:0)
使用.Contains()方法并插入!创建NOT样式语法。
这将是{collection} .Contains(this!= to that);
您也可能对此感兴趣:http://srtsolutions.com/blogs/billwagner/archive/2006/04/10/linq-samples-part-11.aspx
答案 4 :(得分:0)
这是一篇关于在LINQ中使用IN语句的文章。有一点肘部油脂,我相信你可以修改技术来做一个NOT IN。