我正在尝试对可以具有任意数量不同角色的员工列表进行排序。角色本身按 SortOrder
属性排序,我希望员工根据分配给他们的所有角色的最高排序进行排序。
例如:
SortOrder - Role
1 - "Manager"
2 - "Graphics designer"
3 - "Server-tech-guy"
4 - "Web developer"
5 - "Coffee Machine manager"
员工可以既是图形设计师,又可以管理咖啡机。在这种情况下,我只想在对员工列表进行排序时使用“图形设计师”角色的 SortOrder
。
这是我的模型:
public class Employee
{
public int Id { get; set; }
public int BranchId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public double EmploymentPercentage { get; set; }
public double HourlyWage { get; set; }
public List<EmployeeRole> EmployeeRoles { get; set; }
public Branch Branch { get; set; }
}
public class EmployeeRole
{
public int Id { get; set; }
public int EmployeeId { get; set; }
public int RoleId { get; set; }
public Employee Employee { get; set; }
public Role Role { get; set; }
}
public class Role
{
public int Id { get; set; }
public string Title { get; set; }
public int SortOrder { get; set; }
public Branch Branch { get; set; }
}
这是我到目前为止的查询:
List<Employee> employees = await db.Employees
.Include(er => er.EmployeeRoles)
.ThenInclude(r => r.Role)
.Where(b => b.Branch.Id == BranchId)
.OrderByDescending(r => r.EmployeeRoles.Min(s => s.Role.SortOrder))
.ThenByDescending(p => p.EmploymentPercentage)
.ThenBy(n => n.LastName)
.ToListAsync();
在此查询中,我尝试查找每个员工具有最低 SortOrder
编号的角色 (.Min(s => s.Role.SortOrder)
,但是它没有达到我的预期。我得到了
InvalidOperationException: Sequence contains no elements.
最佳答案
当源序列为空时,Min
和 Max
方法的不可空重载会引发异常(例如,如果您有一些 Employee
没有分配角色
)。
但是可为 null 的重载不会抛出异常,而只是返回 null
。因此,解决方案是将不可为 null 的类型提升为相应的可为 null 的类型。另外 ??
运算符可用于为该情况指定特殊值。
就您而言,它可能是这样的:
.OrderByDescending(r => r.EmployeeRoles.Min(s => (int?)s.Role.SortOrder) ?? 0)
关于c# - 如何按角色的排序顺序对员工列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54348983/