我想根据传递的参数在 linq 中添加 2 个不同的连接。 说“isHub”是参数。 如果 isHub = true :我想返回城市列表 如果 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;
}
}
这里是想加入这样的东西
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
}
感谢任何帮助。谢谢
最佳答案
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;
}
关于c# - 如何在linq中添加条件连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53608046/