简体   繁体   English

过滤有什么区别:Dart 中的 Where 和 takeWhile

[英]What is difference between filtering: Where and takeWhile in Dart

I see both of them ( where and takeWhile ) has the same function.. or I might miss something here!我看到他们两个( wheretakeWhile )具有相同的 function .. 否则我可能会在这里错过一些东西!

The documentation for Iterable.where says: Iterable.where的文档说:

Returns a new lazy Iterable with all elements that satisfy the predicate test .返回一个新的惰性Iterable ,其中包含满足谓词test所有元素。

The documentation Iterable.takeWhile says: 文档Iterable.takeWhile说:

Returns a lazy iterable of the leading elements satisfying test .返回满足test前导元素的惰性迭代。

(emphasis added). (强调补充)。

In other words, Iterable.takeWhile will stop iterating once it reaches the first item that does not satisfy the test callback.换句话说,一旦Iterable.takeWhile到达第一个不满足test回调的项目,它将停止迭代。

A concrete example:一个具体的例子:

var list = [1, 1, 2, 3, 5, 8];
print(list.where((x) => x.isOdd).toList()); // Prints: [1, 1, 3, 5]
print(list.takeWhile((x) => x.isOdd).toList()); // Prints: [1, 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM