locked
Linq Statement RRS feed

  • Question

  • User1979860870 posted

    Hi

      In below i want to return only those record whose Id = Parameter id in results variable.

    public HttpResponseMessage GetEmployee(int id)
            {
                Employee employee = db.Employees.Find(id);
                if (employee == null)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee Code : " + id + "not found");
                }
                else
                {
                    var results = (from d in db.Employees
                                   join f in db.Departments
                                   on d.DepartmentId equals f.ID
                                   select new
                                   {
                                       Id = d.ID,
                                       Name = d.Name,
                                       Department = f.Description
                                   }).ToList();
                    return Request.CreateResponse(HttpStatusCode.OK, results);
                }
            }

    Thanks

    Thursday, February 25, 2021 4:08 PM

Answers

  • User-189459990 posted

    If want to filter by parameter id input, you can apply the "Where " to the "Join" results.

    var results = (from d in db.Employees
                    join f in db.Departments
                    on d.DepartmentId equals f.ID
                    where d.DepartmentId == id
                    select new
                    {
                        Id = d.ID,
                        Name = d.Name,
                        Department = f.Description
                    }).ToList();
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 26, 2021 5:09 AM