LinQ选择一个列表作为参数的对象

时间:2016-06-01 15:48:40

标签: c# linq

我使用Linq查询通过我的网络服务从CRM 2013中进行选择。

我的最终实体看起来像这样:

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

Car看起来像这样:

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

House看起来像:

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

现在,我的问题如下:

我只想查询一次crm并检索其中包含所有列表的FOO列表。目前我喜欢这个:

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();

我的目标是将LinQnon-lambda queries一起使用,并使用joingroup-by检索我需要的所有数据,但我并非真的知道如何实现它,任何提示?

全部谢谢

1 个答案:

答案 0 :(得分:3)

我认为你要找的是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()
                         };