我正在尝试使用多个条件过滤List
。最主要的是,如果条件为true
,则必须使用条件,如果条件为false
,则必须使用条件。如果条件是false
,则不应使用该条件进行过滤。下面是我的代码
void performFiltering(bool homeVisits, bool onTheSpotServices)
{
//Check for home and on the spot filtering
if(homeVisits==true)
{
filteredOrganizationList = orgList.where((org) => org.homeVisits==true);
}
else if(onTheSpotServices==true)
{
filteredOrganizationList = orgList.where((org) => org.onTheSpotService==true);
}
else if(homeVisits==true && onTheSpotServices==true)
{
filteredOrganizationList = orgList.where((org) => (org.onTheSpotService==true) ||(org.homeVisits==true) );
}
}
这里我做了简单的if-else
陈述。不严重。但是,当有更多条件时,我将无法执行此操作。幸运的是,这只是两个条件,但是我还有更多的条件。
还请注意,我在上一条语句中使用了OR
Command。这意味着在homeVisits=true
或onTheSpotServices=true
最有效的处理方法是什么?
不需要多个if-else
的级联>
而不是使用具有自定义where
功能的单个test
:
filteredOrganizationList = orgList.where((org) =>
homeVisits && org.homeVisits ||
onTheSpotServices && org.onTheSpotService ||
... // rest of your filter tests
);