如何根据多个条件过滤列表?

问题描述 投票:0回答:1

我正在尝试使用多个条件过滤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=trueonTheSpotServices=true

下获得结果

最有效的处理方法是什么?

arrays list flutter math search
1个回答
1
投票

不需要多个if-else的级联>

而不是使用具有自定义where功能的单个test

filteredOrganizationList = orgList.where((org) =>
  homeVisits && org.homeVisits ||
  onTheSpotServices && org.onTheSpotService ||
  ... // rest of your filter tests      
);
© www.soinside.com 2019 - 2024. All rights reserved.