简体   繁体   中英

Linq - Join resultset of 1 query with another table

I have a Compilations table which have the details of employees and their compliances, I am getting the Employees whose ComplaianceStateId is either 6 or 9.

I have to get the employee FullName of these employees from the master tblEmployee table.

Table Name is tblEmployee and Column Name is FullName

EmployeeID is the Common key between these 2 tables tblEmployee and tblEmployeeCompliation

List<Int> employeeIds = new List<int>();
List<string> employeeNames = new List<string>();

employeeIds = EMPDB.tblEmployeeCompliations.Where( e=> e.IsActive == true && (e.ComplianceStateId == 6 || e.ComplianceStateId == 9)).Select( e => e.EmployeeID).Distinct().ToList();
employeeNames = //**//

I have to get the employee FullName of these employees from the master tblEmployee table

From your requirement, you should select FullName instead of EmployeeID

var result = EMPDB.tblEmployeeCompliations
                  .Where(e => e.IsActive && (e.ComplianceStateId == 6 || e.ComplianceStateId == 9))
                  .Select(e => e.FullName).Distinct().ToList();

You need to join tblEmployeeCompliation and tblEmployee based on EmployeeID .

Example:

var employeeNames =  EMPDB.tblEmployeeCompliations.Join( EMPDB.tblEmployee,
                 comp => comp.EmployeeID,
                 cus => cus.EmployeeID,
                 (comp, cus) => new { comp, cus })
                 .Where(e => e.comp.IsActive && (e.comp.ComplianceStateId == 6 || e.comp.ComplianceStateId == 9))
                 .GroupBy(g=>g.cus.FullName)
                 .Select(x=>x.Key);

OR

var employeeNames  = from comp in EMPDB.tblEmployeeCompliations 
          join cus in EMPDB.tblEmployee on comp.EmployeeID equals cus.EmployeeID
          where comp.IsActive=true && (comp.ComplianceStateId == 6 || comp.ComplianceStateId == 9)
          group new { cus, comp } by new { cus.FullName } into g
          select g.Key.FullName;

Please read this article: LINQ: Distinct() does not work as expected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM