c# - 使用 Select Many 在 LINQ 方法语法中有条件地插入 Where 子句

标签 c# asp.net-mvc linq

不确定这是否可能使用 LINQ 方法链语法或根本无法实现,但如果传递给方法的参数不为空,我想有条件地在链中插入一个 where 类。

这里是我想简化的冗余代码:

public ICollection<Organization> getNetworkServiceRecipients(string serviceId = null)
{
    ICollection<Organization> children = get_all_children();
    if (serviceId != null)
    {
        return children.SelectMany(o => o.receives_these_services)
                        .Where(s => s.serviceId == serviceId)
                        .Select(o => o.serviceRecipient)
                        .Distinct()
                        .ToList();
    }
    else
    {
        return (children.SelectMany(o => o.receives_these_services)
                        .Select(o => o.serviceRecipient)
                        .Distinct()
                        .ToList());
    }
}

我一直在尝试根据 serviceId 是否为 null 以编程方式插入 where 子句。我根据查询语法找到的所有答案,但我无法翻译。有什么建议吗?

最佳答案

如果你不想像 dotnetom 提到的那样在实际的 where 查询中使用它,你可以这样做:

public ICollection<Organization> getNetworkServiceRecipients(string serviceId = null)
{
    var services = get_all_children().SelectMany(o => o.receives_these_services);
    if (serviceId != null)
        services = services.Where(s => s.serviceId == serviceId);

    return services.Select(o => o.serviceRecipient)
                   .Distinct()
                   .ToList();
}

关于c# - 使用 Select Many 在 LINQ 方法语法中有条件地插入 Where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31324328/

相关文章:

c# - 开发大型服务结构应用程序

c# - 在我们的页面内打开外部页面

jquery - 有一个没有文本的 Ajax.ActionLink(显示为只有一个图标的 jQuery 按钮)

c# - 使用 C# LINQ 将过滤后的 List<object> 连接到 List<string>

c# - 使用 LINQ 关联两个列表之间的值?

c# - 使用C#获取Azure服务器中的所有数据库

c# - 如何通过键盘滚动面板?

c# - 我可以在服务器上传递一个转换为 List<int> 的查询字符串吗?

.net - ASP.net MVC 项目是否支持添加动态数据?

c# - 如何使用 WebAPI 和 Linq 序列化部分类