How to Lambda in Extension Methods with multiple Lists?

13

There are the following Objects:

public class Objeto1
{
   public List<Objeto2> PropObj1 {get; set;}
}

public class Objeto2
{
   public List<Objeto3> PropObj2 {get; set;}
}

public class Objeto3
{
   public int PropObj3 {get; set;}
}

I have an Object List1 and I need to get a filtered list of Object1 , only those with PropObj3 == 1 : p>

List<Objeto1> listaObj1 = new List<Objeto1>();
// Suponhamos que listaObj1 já possui valores inseridos.

var resultado = listaObj1.Where(o1 => o1.PropObj1... ).ToList();

In this case, what would the lambda expression look like? Home I'm using Entity Framework .

    
asked by anonymous 10.08.2015 / 22:55

2 answers

9

If it's Entity Framework, I think the list comes from a context, so I will not use a single list to respond. I'll answer from the same context, even because building a list from a data context is completely different from building a list from an operation in memory using Linq:

var lista = contexto.Objetos1
                  .Where(o1 => o1.PropObj1
                                 .Any(o2 => o2.PropObj2
                                              .Any(o3 => o3.PropObj3 == 1)))
                  .ToList();

In pure Linq, see that it would look different:

var sublist = list.PropObj1
                  .Where(o => o.PropObj2.Any(o2 => o2.PropObj3 == 1))
                  .ToList();

I put up a Fiddle for you .

    
10.08.2015 / 23:35
6

I think this is what you want:

var resultado = listaObj1
    .SelectMany(o => o.PropObj1, (objeto1, objeto2) => new { objeto1, objeto2 })
    .SelectMany(o => o.objeto2.PropObj2, (objeto2, objeto3) => new { objeto2, objeto3 })
    .Where(o => o.objeto3.PropObj3 == 1).Select(o => new { o.objeto2.objeto1.PropObj1 })
    .ToList();

SelectMany serves to turn lists of lists into a single sequential list.

Eventually you need to use Select to determine how you want the result.

See working on ideone .

    
10.08.2015 / 22:59