[英]Dart: Filter a list based on another list
I have two objects that look like this:我有两个看起来像这样的对象:
class Field extends RESTModel {
int id;
String name;
String dataType;
int objectId;
}
class FieldKeywordMap extends RESTModel {
int id;
String keywordName;
int objectConfigurationId;
int fieldId;
}
I have a list of FieldKeywordMaps called _fieldKeywordMaps and a list of Fields called _selectedFields.我有一个名为 _fieldKeywordMaps 的 FieldKeywordMaps 列表和一个名为 _selectedFields 的字段列表。 I am writing a function to return a filtered version of _fieldKeywordMaps based on 2 conditions:
我正在编写 function 以根据 2 个条件返回过滤后的 _fieldKeywordMaps 版本:
Filtering based on the first condition works, but Im having trouble determining how to iterate through my _selectedFields list and compare it to the object in _fieldKeywordMaps.基于第一个条件的过滤有效,但我无法确定如何遍历我的 _selectedFields 列表并将其与 _fieldKeywordMaps 中的 object 进行比较。 Here is the code:
这是代码:
selectObjectKeywordMaps() async {
if (selectedObjectConfiguration() != null && selectedObject() != null) {
List<FieldKeywordMap> _maps = _fieldKeywordMaps
.where((keywordMap) =>
keywordMap.objectConfigurationId == selectedObjectConfiguration().id)
.where((filteredKeywordMap) =>
_selectedFields.map((field) => field.id).contains(filteredKeywordMap.id))
.toList();
_selectedObjectKeywordMaps = _maps.toList();
fetchAffectedCustomers();
} else {
_selectedObjectKeywordMaps = [];
}
notifyListeners();
}
.where((filteredKeywordMap) => _selectedFields.map(...))
is inappropriate. .where((filteredKeywordMap) => _selectedFields.map(...))
不合适。 Iterable.map
is used when you want to perform a 1:1 transformation from one Iterable
to another. Iterable.map
用于执行从一个Iterable
到另一个 Iterable 的 1:1 转换。
You instead could do:你可以这样做:
.where((filteredKeywordMap) => _selectedFields.any((field) => field.id == filteredKeywordMap.fieldId))
Note that that can be inefficient;请注意,这可能效率低下; making
_selectedFields
a Map
from id
s to Field
s instead of being a List<Field>
s would make lookups faster and simpler.使
_selectedFields
成为从id
到Field
的Map
而不是List<Field>
将使查找更快更简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.