2017-05-30 200 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