2016-04-14 101 views
0

我需要在LINQ查詢中獲得幫助。LINQ查詢加入三張表

public interface IBrand 
{ 
     int BrandId { get; set; } 
     IEnumerable<IBuyingAgency> BuyingAgencies { get; set; } 
} 

public interface IBuyingAgency 
{ 
     int BuyingAgencyId { get; set; } 
} 

public interface IClientGroup 
{ 
     IBuyingAgency BuyingAgency { get; set; } 
     int ClientGroupId { get; set; } 
} 


1). var brands   = LoggedInUserHelper.GetUser().GetBrands(roles); // returns IEnumerable<Tuple<IBrand, string>> 
2). var buyingAgencies = LoggedInUserHelper.GetUser().GetBuyingAgencies(roles); //IEnumerable<IBuyingAgency> 
3). var clientGroups = LoggedInUserHelper.GetUser().GetClientGroups(roles); //IEnumerable<IClientGroup> 


function IEnumerable<IClientGroup> GetClientGroups(List<int> BrandIds) 
{ 
    var brands   = LoggedInUserHelper.GetUser().GetBrands(roles); // returns IEnumerable<Tuple<IBrand, string>> 
    var buyingAgencies = LoggedInUserHelper.GetUser().GetBuyingAgencies(roles); //IEnumerable<IBuyingAgency> 
    var clientGroups = LoggedInUserHelper.GetUser().GetClientGroups(roles); //IEnumerable<IClientGroup> 

    var lstBrandagencies = brands.Where(brand => BrandIds.Contains(brand.Item1.BrandId) && brand.Item1.BuyingAgencies.Any(ba => buyingAgencies.Contains(ba.BuyingAgencyId))).SelectMany(brand => brand.Item1.BuyingAgencies); 

    var buyingAgencyIDs = lstBrandagencies.Select(b => b.BuyingAgencyId); 

     clientGroups = clientGroups.Where(cg => buyingAgencyIDs.Contains(cg.BuyingAgency.BuyingAgencyId)); 

     return Mapper.Map<IEnumerable<IClientGroup>>(clientGroups.ToList());  

} 

我寫了上述功能,但無法正常工作,它得到所有clientgroups而不是過濾

我想編寫一個查詢來獲取界河滿足以下條件

1. retrieve the brand from brands (above) that matches the list of brandId's passing in as parameter 
2. Than get all the buyingAgencies under brands (1) above which matches with the id's of (2) above 
3. Finally get all clientgroups which matches with the buyingAgency retrieving in step (2) 

所有ClientGroups請你幫忙。

回答

1

你是不是在這行

var buyingAgencyIDs = lstBrandagencies.Select(b => b.BuyingAgencyId); 

從前面的查詢只投射從源2)過濾。

如果我理解正確,你想這樣做。

var lstBrandagencies = (from a in brands 
          where BrandIds.Contains(a.Item1.BrandId) 
          select a).SelectMany (b => b.Item1.BuyingAgencies) 
            .Select (b => b.BuyingAgencyId); 

    var buyingAgencyIDs = from a in buyingAgencies 
          where lstBrandagencies.Contains(a.BuyingAgencyId)       
          select a.BuyingAgencyId; 

    var clientGroupsResult = clientGroups.Where(cg => buyingAgencyIDs.Contains(cg.BuyingAgency.BuyingAgencyId)); 
+0

謝謝。完美運作。 – VVR147493