只是想知道这是否是最有效的方法?有没有一种方法可以在一条语句中包含所有 linq 而不是调用方法,例如子选择或其他方法?
newEmployee = (from emp
in db.employees
select new
{
a.EmployeeID,
a.Username,
Status = emp.GetEmployeeCurrentStatus(a.Username)
}).ToList();
这是返回员工状态的 GetEmployeeCurrentStatus:
public string GetEmployeeCurrentStatus(string username)
{
using (Entities db = new Entities())
{
var times = (from d in db.TimeTables
where d.DateTime == DateTime.Today &&
d.Employee.Username == username
select d)
.OrderByDescending(d => d.TimeID).FirstOrDefault();
return (x.ClockOut == null ? "IN" : "OUT");
}
}
最佳答案
怎么样:
newEmployee = (db.employees.Select(emp => new
{
emp.EmployeeID,
emp.Username,
Status = db.TimeTables
.Where(d => d.Employee.Username == emp.Username
&& d.DateTime == DateTime.Today)
.Select(x => x.ClockOut == null ? "IN" : "OUT")
.FirstOrDefault()
})).ToList();
您的尝试可能看起来更干净并且功能正常。但是,它正在启动辅助数据库调用。这将不利于可扩展性和性能。我发布的版本使用相同的初始数据库连接,将使连接成为 1-1。这将导致更严格、更快的查询以及更低的资源使用。
关于c# - 从 linq 语句中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5181881/