如何在 linq 中添加条件连接?

Che*_*dar 1 c# linq api

我想根据我传递的参数在 linq 中添加 2 个不同的连接。说“isHub”是参数。If isHub = true : 我想返回城市列表 If isHub = false : 我想返回国家列表

这是我当前的查询

   public List<ControlTowerCity> GetControlTowerMapData(bool IsHub)
    {
        using (var context = new LadingControlTowerEntities())
        {
            var mapcityDetail =
            (from SLD in context.ShipmentLocations 
             join CMD in context.CityMasters on SLD.City equals CMD.ID

             select new ControlTowerCity
             { 
                 Name = CMD.Name,

             }).ToList();
            return mapcityDetail;
        }
    }
Run Code Online (Sandbox Code Playgroud)

这里是想添加这样的加入

if(ishHub == true){
  join CMD in context.CityMasters on SLD.City equals CMD.ID
} 
else {
 join CMD in context.CountryMasters on SLD.Country equals CMD.ID
}
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏。谢谢

jav*_*iry 5

using (var context = new LadingControlTowerEntities()) {
    var query = context.ShipmentLocations.AsQueryable();
    // if you have any condition (for example, what you said in comment):
    query = query.Where(t => t.Status == "A");
    IQueryable<ControlTowerCity> resultQuery;
    if (ishHub)
        resultQuery = query.Join(context.CityMasters, t => t.City, t => t.ID, (o, i) => new ControlTowerCity { Name = i.Name });
    else
        resultQuery = query.Join(context.CountryMasters, t => t.Country, t => t.ID, (o, i) => new ControlTowerCity { Name = i.Name });
    var mapcityDetail = resultQuery.ToList();
    return mapcityDetail;
}
Run Code Online (Sandbox Code Playgroud)