sushu
sushu

Reputation: 47

Find list<T> item by searching for combination of keys C#

I want to find the department assigned to an employee on a particular date using List. Combination of employeeID and date will be unique meaning an employee will be assigned to only one department on a particular date.

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.

Upvotes: 2

Views: 93

Answers (2)

Timothy Groote
Timothy Groote

Reputation: 8643

Find may not be the most suitable to use, since in theory there could be more items that match your critaria. perhaps you should consider using Where

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

Where returns an IEnumerable, since there could be more items in the set that match your criteria.

You could use FirstOrDefault, which will return null if no matching items were in the collection, but otherwise will return the first object in the collection.

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

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

Simple, use && without another x =>

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

You can also use LINQ:

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

Side-note: don't use strings for a Date-property but DateTime.

Upvotes: 6

Related Questions