不确定是否可以使用LINQ方法链语法,或者根本不知道,但是如果传递给方法的参数不为null,我想有条件地在链中插入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子句。我找到的所有答案都基于查询语法,但我无法翻译。有什么建议吗?
答案 0 :(得分:4)
如果您不想在dotnetom提到的实际查询位置中使用它,您可以执行以下操作:
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();
}
答案 1 :(得分:3)
您可以尝试这种方法:
public ICollection<Organization> getNetworkServiceRecipients(string serviceId = null)
{
ICollection<Organization> children = get_all_children();
return children.SelectMany(o => o.receives_these_services)
.Where(s => serviceId == null || s.serviceId == serviceId)
.Select(o => o.serviceRecipient)
.Distinct()
.ToList();
}
在这种情况下,如果变量serviceId
为null,则只执行where条件的第一部分,否则第一部分将为真,只有第二部分才重要。
答案 2 :(得分:0)
与dotnetom类似的答案,但使用三元来确定使用哪个lambda
因此serviceId == null
不会按项目执行。
return children.SelectMany(o => o.receives_these_services)
.Where( serviceId == null ? (_ => true) : (s => s.serviceId == serviceId))
.Select(o => o.serviceRecipient)
.Distinct()
.ToList();