-2

I was trying to get employee list which not already available in another list. but im getting only first element from array list. ex : if i try EmployeeId = new int[2] {5, 2}; the list excluding only '5'. So please help me correct my below code.

public JsonResult GetEmployees(int[] EmployeeId)
    {            
        var dbs = new dbContext();

        if (EmployeeId != null)
        {
            foreach (var emp in EmployeeId)
            {
               var EmpList = dbs.Employees.Select(e => new
                   {
                       EmployeeId = e.EmployeeId,                          
                       Name = e.EmployeeName,
                       Job = e.Job.JobName,
                       Currency = e.Currency.CurrencyName,
                       Amount = e.Amount
                   }).Where(o => o.EmployeeId != emp);
              return Json(EmpList, JsonRequestBehavior.AllowGet);
            }
        }   
          return null
    }
Ahmed
  • 21
  • 1
  • 1
  • 5

2 Answers2

0

Have you tried stepping through your code?

Your foreach iterates over your EmployeeId array. Since you have a return statement in your foreach it exits the function at that point and it only uses the first element of your array.

You need something like this:

public JsonResult GetEmployees(int[] EmployeeId)
        {
            var dbs = new dbContext();

            if (EmployeeId != null)
            {                
                var EmpList = dbs.Employees.Where(EmployeeId.Contains(e.EmployeeId))
                .Select(e => new
                {
                    EmployeeId = e.EmployeeId,
                    Name = e.EmployeeName,
                    Job = e.Job.JobName,
                    Currency = e.Currency.CurrencyName,
                    Amount = e.Amount
                }).Where(o => o.EmployeeId != emp);

                return Json(EmpList, JsonRequestBehavior.AllowGet);               
            }

            return null;
        }
Starceaker
  • 631
  • 2
  • 5
  • 14
0

Try this :

var employeeList = dbs.Employees.
             .Where(e => EmployeeId.All(x=> x != e.EmployeeId))
             .Select(e => new
             {
               EmployeeId = e.EmployeeId,                          
               Name = e.EmployeeName,
               Job = e.Job.JobName,
               Currency = e.Currency.CurrencyName,
               Amount = e.Amount
             });
         return Json(EmpList, JsonRequestBehavior.AllowGet);
       }
Mobaruk H
  • 54
  • 1
  • 7