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

标签 c# linq api

我想根据传递的参数在 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/

相关文章:

c# - 使用Linq XDocument读取XML文件的最后n个元素

c# - 在 LINQ C# 中使用 OR 条件

api - Mapbox API/styles/v1/{username} 不反射(reflect)最新的样式数据

api - 为什么 LinkedIn 有 JavaScript 和 Rest API?

c# - 如何使用 Azure.Data.Tables 为 azure 表创建批量更新插入

c# - 多个可选参数路由

c# - 表达式树 Null VisitMember

api - Youtube API 如何获取视频信息

c# - Xml 解析器类的单元测试

c# - WCF 服务代理生成在通过 F5 负载平衡器公开时引发错误