Scala根据标志应用过滤器

时间:2017-12-08 22:21:33

标签: scala collections filter

仅在标志设置为true时应用过滤器,我当前的解决方案如下所示:

(“John_1”,[“a”,”b”,”c”]) //Since there is no John_0, all of the contents are new, so I keep them all
(“John_2”,[])  //Since all of the contents of John_2 appear in John_1, the resulting list is empty (for now, I don’t care about what happened to “c”
(“John_3”,[”c”])  //In this case, “c” is a new item (because I don’t care whether it existed prior to John_2). Again, I don’t care what happened to “a”. 
(“Mary_5”,[“a”,”d”]) //There is no Mary_4 so all the items are kept
(“John_5”,[“c”,”d”,”e”]) //There is no John_4 so all the items are kept.

这个想法是,如果checkAge设置为true,则应该应用过滤器,但如果checkAge为false,则不执行过滤。

简明扼要的表达方式是什么?我提出的最好的是:

val list = List(5,17,25,80)
val checkAge = false
val ageCheckedList = list.filter(i => i>18)

至少可以说是令人困惑的。

2 个答案:

答案 0 :(得分:1)

我认为你拥有的一切都很好。您可以反转逻辑,这样可以使它更具可读性。

list.filter(i => !checkAge || i <= 18)

这基本上表示我们要么不检查年龄,要么年龄在范围内。

答案 1 :(得分:0)

以下内容可能会更清楚地表达您的意图:

   VoyageReservedViewModel Obj = new VoyageReservedViewModel();  
   Obj.preFactorID = new  List<string>(); 
   foreach (var item in result)
   {              
          Obj.preFactorID.Add("My String Value");
   }