英文:
Filter ids from an object list
问题
我需要从对象列表中筛选出ID,并将这些ID存储在一个新数组中。请建议一种方法来完成这个任务。根据以下示例,我需要从“_studentDetails”列表中筛选出ID,并将这些ID存储在“_idList”数组中。
示例:
List<int> _idList = [];
List<Student> _studentDetails = [];
_studentDetails = [
Student(id: 1, name: 'Peter', age: 14),
Student(id: 2, name: 'Anne', age: 20),
];
英文:
I need to filter ids from an object list and add those id list to a new array.Please suggest a way to do this.As per the below example I need to filter the ids from the '_studentDetails' list and store those ids in '_idList' array.
Example:
List<int> _idList = [];
List<Student> _studentDetails = [];
_studentDetails = [
Student(id:1 , name:'Peter' , age: 14),
Student(id:2 , name:'Anne' , age: 20),
];
答案1
得分: 1
你可以使用 list.map()
方法来实现这个,遍历列表项,对于每个项,返回其属性 id
的值,然后将所有返回的值转换为列表:
List<int> _idList = _studentDetails.map((student) => student.id).toList();
英文:
You can achieve this using list.map()
method<br>
you loop through the list items and for every one you return the value of its preoperty id
then convert all the returned values to list:
List<int> _idList = _studentDetails.map((student) => student.id).toList();
答案2
得分: 0
如果你只想要ID列表,你可以使用.map
方法:
List<int> _idList = [];
List<Student> _studentDetails = [];
_studentDetails = [
Student(id:1 , name:'Peter' , age: 14),
Student(id:2 , name:'Anne' , age: 20),
];
_idList.addAll(
_studentDetails.map((student) => student.id),
);
英文:
If you just want the list of ids, you can use the method .map
:
List<int> _idList = [];
List<Student> _studentDetails = [];
_studentDetails = [
Student(id:1 , name:'Peter' , age: 14),
Student(id:2 , name:'Anne' , age: 20),
];
_idList.addAll(
_studentDetails.map((student) => student.id),
);
答案3
得分: 0
你还可以使用 forEach() 循环 来实现这一点。
下面是代码:
void main(){
List<int> _idList = [];
List<Student> _studentDetails = [];
_studentDetails = [
Student(id: 1, name: 'Peter', age: 14),
Student(id: 2, name: 'Anne', age: 20),
];
_studentDetails.forEach((element) {
_idList.add(element.id);
});
print(_idList);
}
class Student{
int id;
String? name;
int? age;
Student({required this.id, required this.name, required this age});
}
英文:
You can also achieve this using forEach() loop
Below the code:
void main(){
List<int> _idList = [];
List<Student> _studentDetails = [];
_studentDetails = [
Student(id:1 , name:'Peter' , age: 14),
Student(id:2 , name:'Anne' , age: 20),
];
_studentDetails.forEach((element) {
_idList.add(element.id);
} );
print(_idList);
}
class Student{
int id;
String? name;
int? age;
Student({required this.id, required this.name, required this.age});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论