我的Distinct查询工作正常,但是我需要在另一个方法中放入WHERE子句。
这是我检索不同经理的工作查询
public static IEnumerable<DTO.Employee> GetDistinctMgrs()
{
IEnumerable<DTO.Employee> managers = EmpCache.EmployeeList.GroupBy(x => x.MgrID).Select(x => x.FirstOrDefault());
return managers;
}
在这里,我试图从哪里选拔不同的经理人名单中的雇员经理人。但是有了WHERE子句,我得到“枚举没有结果”
public static IEnumerable<DTO.Employee> GetDefaultMgr(string EMPID)
{
IEnumerable<DTO.Employee> manager = EmpCache.EmployeeList
.Where(s => s.EmpID == EMPID)
.GroupBy(x => x.MgrID)
.Select(x => x.FirstOrDefault());
return manager; //<- "Enumeration yielded no results"
}
答案 0 :(得分:1)
您正在做的是向数据库发送请求,当请求完成时,您进行groupby等操作。
因此,当数据库不返回任何内容时,您会得到异常
这是我要怎么做
public static IEnumerable<DTO.Employee> GetDefaultMgr(string EMPID)
{
IEnumerable<DTO.Employee> manager = EmpCache.EmployeeList
.Where(s => s.EmpID == EMPID)
.GroupBy(x => x.MgrID);
if(manager?.Count()>0)
return manager.Select(x => x.First());
return null;
}
答案 1 :(得分:1)
我会做
public static IEnumerable<DTO.Employee> GetDefaultMgr(string EMPID)
{
IEnumerable<DTO.Employee> manager =
from mng in EmpCache.EmployeeList
where mng.EmpID.ToLower() == EMPID.ToLower()
orderby mng.MgrID
select mng;
return manager;
}
或
public static IEnumerable<DTO.Employee> GetDefaultMgr(string EMPID)
{
IEnumerable<DTO.Employee> manager = EmpCache.EmployeeList
.Where(s => s.EmpID.ToLower() == EMPID.ToLower())
.GroupBy(x => x.MgrID)
.Select(x => x.FirstOrDefault()).ToList();
return manager; //<- "Enumeration yielded no results"
}
基于您的新问题
public static string GetDefaultMgr(string EMPID)
{
string managerID = EmpCache.EmployeeList
.Where(s => s.EmpID.ToLower() == EMPID.ToLower())
.GroupBy(x => x.MgrID)
.Select(x => x.MgrID).FirstOrDefault().ToString();
return managerID; //<- "Enumeration yielded no results"
}