[英]Dart How to compare UIDs of two Lists and Generate third List in Flutter
[英]Dart/Flutter - Compare two List<dynamic> if they have the same value of id
我有两个List<dynamic>
,我想弄清楚如何检查id
字段中是否有相同的值
List list1 = [
{"id": 2, "name": "test1"},
{"id": 3, "name": "test3"}
];
List list2 = [
{"id": 2, "name": "test1"}
];
我试过这个,但它返回给我错误
var isMatch = (list1.toSet().intersection(list2.toSet()).length > 0);
你不能那样比较,因为你不能像 Boken 所说的那样比较动态,你需要为你的对象创建一个类并实现一个基本的搜索,你可以将 list2 转换成一个集合,使搜索不那么复杂(包含函数)
void main() {
List list1 = [
MyObject(2,"test"),
MyObject(3,"test1")
];
List list2 = [
MyObject(4,"test")
];
for(int i=0;i<list1.length;i++){
if(list2.contains(list1[i])){
// do your logic
print(true);
break;
}
}
}
class MyObject{
int id;
String name;
MyObject(int id,String name){
this.id = id;
this.name = name;
}
// redifine == operator
bool operator ==(o) => (o as MyObject).id == this.id;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.