list - 如何将类列表的成员转换为列表在一行代码中?
问题描述
我有一个List<MyClass> myClass;
,我想List<String> myList;
从所有 myClass.item 中获取,有没有一种方法可以转换它?
解决方案
您可以使用 List 类中的 map 方法遍历整个列表。最后不要忘记调用 toList,因为 Dart 的 map 返回一种 Iterable。请看下面的代码。
class Employee {
int id;
String firstName;
String lastName;
Employee(
this.id,
this.firstName,
this.lastName,
);
}
void main() {
List<Employee> employees = <Employee>[
Employee(1, "Adam", "Black"),
Employee(2, "Adrian", "Abraham"),
Employee(3, "Alan", "Allan"),
];
List<String> myList = employees.map((item)=>item.firstName).toList();
print(myList);
}
推荐阅读
- javascript - 用户检查单选按钮时如何更新价格
- vb.net - Sqlite 在一个读取的数据库上抛出空异常,但不是另一个
- regex - RewriteRule 的 mod_rewrite 问题
- dart - Dart 中如何专门化(覆盖)类字段?
- python - history.append() throws "IndexError: index 184 is out of bounds for axis 0 with size 184"
- prolog - Prolog: show truth table for arbitrary expression using is/2 for some subexpressions
- javascript - create react embeddable widget from create-react-app
- google-cloud-platform - Can not set natIP to an IP resource
- c# - C# UWP ScrollViewer 改变 HorizontalScrollBarVisibility
- python-3.x - Python 与谷歌云语言 api 问题?