Pier Giorgio Misley
Pier Giorgio Misley

Reputation: 5351

LinQ select an object with a list as parameter

I'm using Linq queries to select from CRM 2013 with my webservice.

My final entity looks like this:

class FOO{
    Guid fooId{get;set;}
    String fooName{get;set;}
    List<Car> fooCars{get;set;}
    List<House> fooHouses{get;set;}
}

Where Car looks like this:

class Car{
    Guid carId{get;set;
    String carName{get;set;}
    Guid carFooId{get;set;}
}

And House looks like:

class House{
    Guid houseId{get;set;}
    String houseName{get;set;}
    Guid houseFooId{get;set;}
}

Now, my problem is the following:

I wanna query only once the crm and retrieve a list of FOO with all lists inside it. At the moment I do like this:

List<FOO> foes = crm.fooSet
  .Where(x => x.new_isActive != null && x.new_isActive.Value = true)
  .Select(x => new FOO(){
    fooId = x.Id,
    fooName = x.Name,
    fooCars = crm.carSet.Where(c => c.fooId == x.Id)
                          .Select(c => new Car(){
                             carId = c.Id,
                             carName = c.Name,
                             carFooId = c.fooId
                           }).ToList(),
    fooHouses = crm.houseSet.Where(h => h.fooId == x.Id)
                          .Select(h => new House(){
                             houseId = h.Id,
                             houseName = h.Name,
                             houseFooId = h.fooId
                           }).ToList()
}).ToList();

My aim is to use LinQ with the non-lambda queries and retrieve all the datas I need with a join and a group-by, but I don't really know how to achieve it, any tip?

Thanks all

Upvotes: 1

Views: 3557

Answers (1)

ocuenca
ocuenca

Reputation: 39326

I think what you are looking for is a group join:

var query= from f in crm.fooSet 
           join c in crm.carSet on c.fooId equals f.Id into cars
           join h in crm.houseSet  on h.fooId equals f.Id into houses
           where f.new_isActive != null && f.new_isActive.Value == true
           select new FOO{ fooId = f.Id,
                           fooName = f.Name,
                           fooCars=cars.Select(c => new Car(){
                                                              carId = c.Id,
                                                              carName = c.Name,
                                                              carFooId = c.fooId
                                                              }).ToList(),
                           fooHouses=houses.Select(h => new House(){
                                                              houseId = h.Id,
                                                              houseName = h.Name,
                                                              houseFooId = h.fooId
                                                                   }).ToList()
                         };

Upvotes: 4

Related Questions