有没有办法根据如下条件在 dart 中拆分列表:
[1, 2, 3, 4, 5, 6, 7, 8] (A sample list)
After splitting it based on i % 2 == 0 condition,
it would generate the following two lists:
1) [1, 3, 5, 7]
2) [2, 4, 6, 8]
Run Code Online (Sandbox Code Playgroud)
我知道我可以简单地编写一个循环来遍历所有元素并检查创建两个子列表的条件。但是 Dart 中有没有更短的函数方式呢?提前致谢!
如果您想经常这样做,那么在您的项目中创建一个扩展方法来执行您想要的操作可能是个好主意。我提出了以下设计,它应该以通用且有效的方式工作:
void main() {
final s_list = [1, 2, 3, 4, 5, 6, 7, 8];
final match = s_list.splitMatch((element) => element % 2 == 0);
print(match.matched); // [2, 4, 6, 8]
print(match.unmatched); // [1, 3, 5, 7]
}
extension SplitMatch<T> on List<T> {
ListMatch<T> splitMatch(bool Function(T element) matchFunction) {
final listMatch = ListMatch<T>();
for (final element in this) {
if (matchFunction(element)) {
listMatch.matched.add(element);
} else {
listMatch.unmatched.add(element);
}
}
return listMatch;
}
}
class ListMatch<T> {
List<T> matched = <T>[];
List<T> unmatched = <T>[];
}
Run Code Online (Sandbox Code Playgroud)
快速解决方案:
var s_list = [1, 2, 3, 4, 5, 6, 7, 8];
s_list.where( (el) => el % 2 == 0 ).toList();
s_list.where( (el) => el % 2 != 0 ).toList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4615 次 |
| 最近记录: |