Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Select Statements - Where Not In

I'm trying to write up the LINQ statement that is equivalent to:

select e.EmployeeID, EmployeeName = e.FirstName + ' ' + e.LastName
from Employees e
where e.EmployeeID not in
(
    select EmployeeID from Managers
)

I think I'm pretty close with the following:

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
}

I'm trying to put this into a Html.DropDownList.

like image 992
kntcnrg Avatar asked Jun 18 '09 20:06

kntcnrg


3 Answers

I'm not exactly sure what the proper query notation for this is, but the following expanded syntax will get the job done

var result = Employees
  .Where( e => !Managers.Where(m => m.EmployeeId == e.EmployeeId).Any())
  .Select( e => new { EmployeeId = e.EmployeeId, EmployeeName = e.FirstName + ' ' + e.LastName);
like image 102
JaredPar Avatar answered Oct 26 '22 15:10

JaredPar


Using Any:

from e in Employees
where !Managers.Any(m => m.EmployeeID == e.EmployeeID)
select new
{
    e.EmployeeID,
    EmployeeName = e.FirstName + ' ' + e.LastName
}

Or, using a left join:

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
}
like image 44
Bryan Watts Avatar answered Oct 26 '22 14:10

Bryan Watts


You can get the result you want with a 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);
}

output:

1 John Smith
3 Eddie Punchclock
like image 32
Handcraftsman Avatar answered Oct 26 '22 13:10

Handcraftsman