Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expressions, how to search inside an object?

Tags:

c#

lambda

I'm starting to love Lambda expressions but I'm struggling to pass this wall:

public class CompanyWithEmployees {
    public CompanyWithEmployees() { }
    public Company CompanyInfo { get; set; }
    public List<Person> Employees { get; set; }
}

My search:

List<CompanyWithEmployees> companiesWithEmployees = ws.GetCompaniesWithEmployees();
CompanyWithEmployees ces = companiesWithEmployees
        .Find(x => x.Employees
        .Find(y => y.PersonID == person.PersonID));

So, I want to get the Object "CompanyWithEmployees" that have that Person (Employee) that I'm looking for, but I'm getting "Cannot implicit convert 'Person' To 'bool')" which is correct, but if I'm not passing the Person object, how can the first Find executes?

like image 356
balexandre Avatar asked Jan 06 '09 08:01

balexandre


2 Answers

Because you want to check for existance, perhaps try:

ces = companiesWithEmployees
        .Find(x => x.Employees
        .Find(y => y.ParID == person.ParID) != null);

This will check for any Person with the same ParID; if you mean the same Person instance (reference), then Contains should suffice:

ces = companiesWithEmployees
        .Find(x => x.Employees.Contains(person));
like image 111
Marc Gravell Avatar answered Nov 08 '22 19:11

Marc Gravell


Find() returns the found object. Use Any() to just check whether the expression is true for any element.

var ces = companiesWithEmployees
    .Find(x => x.Employees
    .Any(y => y.PersonID == person.PersonID));
like image 21
David Schmitt Avatar answered Nov 08 '22 18:11

David Schmitt