不确定这是否可能使用 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/