基于所选多个复选框筛选列表的最佳方法

时间:2017-03-08 10:05:42

标签: c#

目前我得到了可能的组合数(复选框数量的因子)并写了很多if语句,如:

假设我有3个复选框:

liferay-portal/portal-impl/src/META-INF/portal-model-hints.xml

即使这符合要求,我也不认为它是一种最佳解决方案,考虑到未来复选框的数量可能会增加,并且组合的数量会变得很大。

如果在根据选中的复选框过滤列表时存在已知模式,我会徘徊吗?

4 个答案:

答案 0 :(得分:1)

将布尔值与每个字段进行比较 试试这个:

return _callsData.Where(x => x.IncomingCall == IncludeIncomingCalls  && x.OutgoingCall == IncludeOutgoingCalls && x.ExternalCall== IncludeExternalCalls);

答案 1 :(得分:0)

试试这个:

return _callsData.Where(x => x.IncomingCall==IncludeIncomingCalls  && x.OutgoingCall==IncludeOutgoingCalls  && x.ExternalCall==IncludeExternalCalls);

答案 2 :(得分:0)

请注意,您可以撰写IQueryable。您可以根据需要添加其他Where子句。

var result = callsData.Select(x => x);

if (IncludeIncomingCalls) {
    result = result.Where(x => x.IncomingCall);
}
else {
    result = result.Where(x => !x.IncomingCall);
}

if (IncludeOutgoingCalls) {
    result = result.Where(x => x.OutgoingCall);
}
else {
    result = result.Where(x => !x.OutgoingCall);
}

if (IncludeExternalCalls) {
    result = result.Where(x => x.ExternalCall);
}
else {
    result = result.Where(x => !x.ExternalCall);
}

return result;

我只是将其显示为一般模式。对于您的用例,Ubiquitous Developers的解决方案更易于阅读和理解。

但是如果条件比只有一点标志更复杂,那么这种模式可能会派上用场。仅作为一个例子:

if (ShowOnlyActive) {
    result = result.Where(x => x.State == CallState.Active);
}
else {
    result = result.Where(x => x.State == CallState.Deleted || x.State == CallState.Inactive);
}

偏离主题,只是为了进一步说明这个一般概念:向IQueryable添加附加子句可用于将查询的一部分重构为辅助或扩展方法,例如实现分页。

public interface IPageableQuery {
    // The page size (i.e. the number of elements to be displayed).
    // The method processing the Query will Take() this number of elements.
    int DisplayLength { get; set; }

    // The number of elements that have already been displayed.
    // The method processing the Query will Skip() over these elements.
    int DisplayStart { get; set; }
}

public static IQueryable<T> ApplyPaging<T>(this IQueryable<T> entries, IPageableQuery query)
    where T : class {
    if (query.DisplayStart >= 0 && query.DisplayLength > 0) {
        return entries.Skip(query.DisplayStart).Take(query.DisplayLength);
    }
    return entries;
}

答案 3 :(得分:0)

您可以使用以下模式:

//some checkboxes
CheckBox chkA = ...
CheckBox chkB = ...
CheckBox chkC = ...

//build up your filters
var filters = new List<Predicate<SomeEntity>>();
filters.Add(e => chkA.Checked && e.IsA);
filters.Add(e => chkB.Checked && e.IsB);
filters.Add(e => chkC.Checked && e.IsC);

//And now simply apply the filters
var entities = ... //some enumerable of SomeEntity
var filteredEntities = entities.Where(e => filters.All(filter => filter(e)));

请注意,只有当IsAIsBIsC排除条件时,这才能正常运行,但这似乎是您目前所拥有的设置。