Selecting employees in certain departments using LINQ I am trying to select the DepartmentName from Employee Table based on where condition. Is any way to simplify the code?

List&lt;Department&gt; lstdepartment=(from i in _context.Department 
                                select i).ToList();

    List&lt;Employee&gt;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=&gt;w.DepartmentId==e.DepartmentId)
                                .Select(x=&gt;x.DepartmentName).SingleOrDefault();
                            }).ToList();
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();