有没有办法让下面的lambda表达式将方法调用ConvertFilterType(filter.FilterTypeId)
移动到一个变量中,这样就不会为每个条件重复调用它?
此if语句确保集合包含所有必需的过滤器。
if (run.Filters.All(
filter => (ConvertFilterType(filter.FilterTypeId) != FilterType.A)
&& (ConvertFilterType(filter.FilterTypeId) != FilterType.B)
&& (ConvertFilterType(filter.FilterTypeId) != FilterType.C)
&& (ConvertFilterType(filter.FilterTypeId) != FilterType.D)
&& (ConvertFilterType(filter.FilterTypeId) != FilterType.E)))
{
throw new ArgumentException();
}
答案 0 :(得分:6)
if (run.Filters.All(
filter => {
FilterType t = ConvertFilterType(filter.FilterTypeId);
return
t != FilterType.A && t != FilterType.B && t != FilterType.C && t != FilterType.D && t != FilterType.E;
}))
{
throw new ArgumentException();
}
答案 1 :(得分:3)
以下是一些示例代码,但我不知道您的Filters集合中的项目类型是什么,以了解该方法的参数需要是什么。
if (run.Filters.All(filter => { return IsFilterAllowed(filter); } )
{
throw new ArgumentException();
}
private bool IsFilterAllowed(FiltersItemType filter)
{
FilterType t = ConvertFilterType(filter.FilterTypeId);
return
t != FilterType.A &&
t != FilterType.B &&
t != FilterType.C &&
t != FilterType.D &&
t != FilterType.E;
}
答案 2 :(得分:2)
King的答案是要走的路,但看起来你也可以做到这一点。
FilterType[] notTheseFilters = new FilterType[] { FilterType.A, FilterType.B...};
bool result = !Filters.Any(f =>
notTheseFilters.Contains(ConvertFilterType(f.FilterTypeId)));
答案 3 :(得分:0)
如果我的逻辑对我有用,你也可以这样做
var filterTypesToAvoid = new[]{
FilterType.A,
FilterType.B,
FilterType.C,
FilterType.D,
FilterType.E
};
if (run.Filters.All(
filter => !filterTypesToAvoid.Contains(ConvertFilterType(filter.FilterTypeId))
))
{
throw new ArgumentException();
}
这样LINQ查询中就不需要括号。
答案 4 :(得分:0)
要扩展brader24提出的建议,你可以试试:
if (run.Filters.All(IsFilterAllowed))
{
throw new ArgumentException();
}
private bool IsFilterAllowed(FiltersItemType filter)
{
FilterType t = ConvertFilterType(filter.FilterTypeId);
return
t != FilterType.A &&
t != FilterType.B &&
t != FilterType.C &&
t != FilterType.D &&
t != FilterType.E;
}