1
\$\begingroup\$

I am trying to select the DepartmentName from Employee Table based on where condition. Is any way to simplify the code?

List<Department> lstdepartment=(from i in _context.Department 
                                select i).ToList();

    List<Employee>lstEmployee=(from e in _context.Employee
                            where e.EmployeeId=EmployeeId
                            select new EmployeeInfo
                            {
                                EmployeeId = e.EmployeeId,
                                FirstName = e.FirstName,
                                LastName = e.LastName,
                                MiddleName = e.MiddleName,
                                //Need code simplifiaction
                                DepartmentName=lstdepartment.Where(w=>w.DepartmentId==e.DepartmentId)
                                .Select(x=>x.DepartmentName).SingleOrDefault();
                            }).ToList();
\$\endgroup\$
3
\$\begingroup\$
lstdepartment

We don't use Hungarian notation with prefixes like lst in C#. It's just departments


This is notepad coding but you can use a join to get the matching deparment

var results = 
    from e in _context.Employee
    join d in _context.Department on e.DepartmentId equals d.DepartmentId
    where e.EmployeeId = EmployeeId
    select new EmployeeInfo
    {
        EmployeeId = e.EmployeeId,
        FirstName = e.FirstName,
        LastName = e.LastName,
        MiddleName = e.MiddleName,    
        DepartmentName= d.DepartmentName
    }).ToList();

although this is not yet exactly what you have because this will yield only exact matches. If you want deparment-name to be null then you need a left join and I think this should work:

var results = 
    from e in _context.Employee
    join d in _context.Department on e.DepartmentId equals d.DepartmentId into ds
    from d in ds.DefaultIfEmpty()
    where e.EmployeeId = EmployeeId
    select new EmployeeInfo
    {
        EmployeeId = e.EmployeeId,
        FirstName = e.FirstName,
        LastName = e.LastName,
        MiddleName = e.MiddleName,    
        DepartmentName= d?.DepartmentName
    }).ToList();
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.