1

我的 Web 应用程序中有一个 linq to sql 查询。我刚刚意识到它是根据员工编号对结果进行升序排序。有没有办法让它按照提供的顺序返回结果?

我的代码如下:

 public static queryClass[] GetEmpData(int empID1, int empID2, int empID3, int empID4, int empID5, int empID6, int empID7, int empID8, int empID9, int empID10)
    {

        using(var context = new EmpInfoDataContext())
        {
            var query = from e in context.EmployeeMasters
                        join j in context.JobClasses on e.JobClass equals j.JobClass
                        where e.EmployeeNo == empID1 || e.EmployeeNo == empID2 || e.EmployeeNo == empID3 || e.EmployeeNo == empID4 || e.EmployeeNo == empID5 || e.EmployeeNo == empID6 || e.EmployeeNo == empID7 || e.EmployeeNo == empID8 || e.EmployeeNo == empID9 || e.EmployeeNo == empID10
                        select new queryClass{firstName = e.FirsName, lastName = e.LastName, employeeNo = e.EmployeeNo, department = j.Department};
            return query.ToArray();
        }
    }

提前致谢。

4

1 回答 1

1

尝试执行以下操作:

var employeeIds = new List<int> { empID1, empID2, empID3, empID4, empID5, empID6, empID7, empID8, empID9, empID10 };

var query = from e in context.EmployeeMasters
            join j in context.JobClasses on e.JobClass equals j.JobClass
            where employeeIds.Contains(e.EmployeeNo)
            select new queryClass {
              firstName = e.FirsName, 
              lastName = e.LastName, 
              employeeNo = e.EmployeeNo, 
              department = j.Department,
              orderNum = e.EmployeeNo == empID1 ? 1 :
                         e.EmployeeNo == empID2 ? 2 :
                         e.EmployeeNo == empID3 ? 3 :
                         e.EmployeeNo == empID4 ? 4 :
                         e.EmployeeNo == empID5 ? 5 :
                         e.EmployeeNo == empID6 ? 6 :
                         e.EmployeeNo == empID7 ? 7 :
                         e.EmployeeNo == empID8 ? 8 :
                         e.EmployeeNo == empID9 ? 9 :
                         e.EmployeeNo == empID10 ? 10 : 11
            };
return query.OrderBy(x => x.orderNum).ToArray();

添加将根据参数中值的顺序设置的自定义顺序属性。有点难看,但根据您对此功能的签名满足要求(我还添加了employeeIds List<int>上述内容以使您的查询更具可读性)。

于 2013-02-26T19:27:10.360 回答