Dart如何从两个List取相同数据?where方法返回空列表求助
问题描述
我想要从data和data2这两个List中获取相同的数据,但使用where函数后得到的是空列表,请问该如何解决?感谢帮助。
List data = [ { "isin": "ANQ129", "label": "cocoa", "swatch_value": null, "products": [ 118 ] }, { "isin": "ANQ103", "label": "apple", "swatch_value": null, "products": [ 121, 128 ] }, { "isin": "ANQ150", "label": "milk", "swatch_value": null, "products": [ 122 ] }, { "isin": "ANQ160", "label": "coconut", "swatch_value": null, "products": [ 130 ] }, { "isin": "ANQ123", "label": "cherry", "swatch_value": null, "products": [ 126 ] } ]; List data2 = [ { "isin": "ANQ129", "label": "cocoa", "swatch_value": null, "products": [ 118 ] }, { "isin": "ANQ128", "label": "dark chocolate", "swatch_value": null, "products": [ 120, 127 ] }, { "isin": "ANQ103", "label": "apple", "swatch_value": null, "products": [ 121, 128 ] }, { "isin": "ANQ133", "label": "milk", "swatch_value": null, "products": [ 122 ] }, { "isin": "ANQ142", "label": "coconut", "swatch_value": null, "products": [ 130 ] }, { "isin": "ANQ123", "label": "cherry", "swatch_value": null, "products": [ 126 ] } ]; var filtered = data.where((e) => data2.contains(e['isin'])).toList(); print(filtered.toString());
问题原因与解决方法
错误原因
你写的data2.contains(e['isin'])是在判断data2列表是否包含字符串类型的isin值,但data2里的元素都是Map对象,根本不是字符串,所以这个判断永远返回false,自然得到空列表。
解决方法
方法一:用Set优化查询性能(推荐)
先把data2里所有元素的isin提取出来存到Set中(Set的contains查询速度远快于列表),再用这个Set过滤data:
// 提取data2的所有isin到Set var data2Isins = data2.map((item) => item['isin']).toSet(); // 过滤出data中isin存在于data2的元素 var filtered = data.where((e) => data2Isins.contains(e['isin'])).toList(); print(filtered.toString());
方法二:直接遍历判断(适合小数据量)
如果数据规模不大,也可以直接在where里检查data2中是否有元素的isin和当前元素相等:
var filtered = data.where((item) => data2.any((item2) => item2['isin'] == item['isin']) ).toList(); print(filtered.toString());
效果说明
两种方法都会返回data中与data2拥有相同isin的元素,也就是示例里的cocoa、apple、cherry这三个条目。
内容的提问来源于stack exchange,提问作者Deepak
相关产品推荐
相关产品推荐

