2016-04-14 66 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