c# - 从 linq 语句中调用函数

标签 c# linq linq-to-entities

只是想知道这是否是最有效的方法?有没有一种方法可以在一条语句中包含所有 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/

相关文章:

c# - 异步编程中的线程状态管理

c# - 在 C# 中识别操作系统详细信息

c# - 如何将带条件的嵌套 foreach 循环转换为 LINQ

linq - IEnumerable<T>.Count() 与 List<T>.Count 与 Entity Framework

c# - 使用 LINQ-to-Entities 搜索时忽略空字符串

sql - 等效于 SQL 'IS NULL' 的 Entity Framework

c# - 制作 Selenium 无需等待元素

c# - 查找与我的 ViewModel 关联的 View 的所有者

linq - 在 PowerShell 中调用静态通用 LINQ 扩展方法

C# PredicateBuilder 实体 : The parameter 'f' was not bound in the specified LINQ to Entities query expression