2017-05-30 249 views
1

我想找到分配给员工使用列表中的特定日期的部门组合查找列表 项目。 employeeID和日期的组合将是唯一的,这意味着员工只能在特定日期被分配到一个部门。 通过搜索键C#

List<clsEmployee> _items = new List<clsEmployee>(); 

_items.Add(new clsEmployee() 
{EmpId=100,Date="05/05/2017",DeptAssigned="Grocery"}); 
_items.Add(new clsEmployee() 
{EmpId=100,Date="06/05/2017",DeptAssigned="Clothing"}); 
_items.Add(new clsEmployee() 
{EmpId=100,Date="07/05/2017",DeptAssigned="Crockery"}); 

_items.Add(new clsEmployee() 
{EmpId=101,Date="05/05/2017",DeptAssigned="cosmetics"}); 
_items.Add(new clsEmployee() 
{EmpId=101,Date="06/05/2017",DeptAssigned="gardening"}); 
_items.Add(new clsEmployee() 
{EmpId=101,Date="07/05/2017",DeptAssigned="grocery"}); 


    clsEmployee objEmployee = new clsEmployee(); 
    objEmployee = _items.Find(x => x.EmpId == 100); 
//i want something like objEmployee = _items.Find(x => x.EmpId==100 
//&& x => x.Date="05/05/2017"); 
string DeptAssignedToEmp = objEmployee.DeptAssigned; 
//expected result - grocery in this case. 
+0

作为一个侧面说明 - 仅仅是一个建议: 你会更安全具有不DeptAssigned作为一个简单的字符串。至少使用某种常量,甚至更好的枚举。 这种方式,你会避免拼写错误和区分大小写的比较 –

+1

不要使用字符串来表示日期 – Steve

回答

5

简单,使用&&没有其他x =>

clsEmployee objEmployee = _items.Find(x => x.EmpId == 100 && x.Date == "05/05/2017"); 

你也可以使用LINQ:

clsEmployee objEmployee = _items.FirstOrdefault(x => x.EmpId == 100 && x.Date == "05/05/2017"); 

边注:请不要使用字符串的日期 - 属性,但DateTime

0

Find未必是最适合使用,因为在理论上有可能是符合您critaria更多的项目。也许你应该考虑使用Where

var matchingItems = _items.Where(x => x.EmpId==100 && x.Date=="05/05/2017"); 

Where返回IEnumerable,因为有可能是在符合条件的设定更多的项目。

你可以使用FirstOrDefault,这将返回null如果没有匹配的项目是收集,否则将返回集合中的第一个对象。

var matchingItem = _items.FirstOrDefault(x => x.EmpId==100 && x.Date=="05/05/2017"); 
if(matchingItem == null) 
{ 
    //nothing matched your criteria 
} 
+0

问题洛尔时拷贝粘贴超出原质询 –

+4

的为什么'Where'后跟一个'FirstOrDefault'我要小心?为什么不单独使用FirstOrDefault? –

+1

您可以改为'FirstOrDefault(x => x.EmpId == 100 && x.Date ==“05/05/2017”)'。 – juharr