Jose3d
Jose3d

Reputation: 9277

Deeper level LINQ query in a lambda expression

I would like to get those employees who have a phone number == "666666" using a LINQ query.

These are the class definitions:

public class Employees
{
    public List<Phones> Phones{get;set}
}
public class Phones
{
    public string Id{get;set;}
    public string Number{get;set;}
}

This is my query (my doubt indicated as ???):

var employees= data.GetEmployees()
                   .Where(e=> e.Phones ???i need to navigate a level below phones ???)
                   .Select(e => new Employee() 
                   {     
                        Id=e.Id,
                        Name=e.Name 
                   });

My problem is I don't know how to go a deeper level in this LINQ expression, because in e=>e... I have access to Phones as an IEnumerable but I would like to navigate to Phone's properties.

Upvotes: 2

Views: 265

Answers (3)

Saeed Amiri
Saeed Amiri

Reputation: 22555

var employees= data.GetEmployees()
               .Where(e=> e.Phones.Contains(x=>x.Number == "666666"))
               .Select(e => new Employee() 
               {     
                    Id=e.Id,
                    Name=e.Name 
               });

Upvotes: 1

JaredPar
JaredPar

Reputation: 754585

The easiest way to do this is to use nested LINQ queries. In this case you should look at the Any method.

var employees= data
  .GetEmployees()
  .Where(e => e.Phones.Any(p => p.Number == "666666"))
  .Select(e => new Employee() {
    Id = e.Id,
    Name = e.Name
  });

Upvotes: 3

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41757

The parameter passed to the where method is merely a function that returns true or false for each given element, all methods (including LINQ ones (subject to accessing ref/out params etc)) can still be called within it:

var employees= data.GetEmployees()
               .Where(e => e.Phones.Any(p => p.Number == "666666"))
               .Select(e => new Employee() 
               {     
                    Id=e.Id,
                    Name=e.Name 
               });

Upvotes: 3

Related Questions