【发布时间】:2023-03-27 00:20:02
【问题描述】:
我有两个列表,我想通过比较两个列表来创建一个新列表,新列表应该只包含每个列表中包含的元素。
List1=[[id: 1, label: 'cocoa'],[id: 2, label: 'apple'],[id: 3, label: 'cherry'],[id: 4, label: 'banana'],[id: 5, label: 'melon'],[id: 6, label: 'orange'],[id: 7, label: 'pineapple'],[id: 8], label: 'strawberry']
List2=[2,5,7,8]
expectedList = [[id: 2, label: 'apple'],[id: 5, label: 'melon'],[id: 7, label: 'pineapple'],[id: 8], label: 'strawberry']]
下面是真正的代码:
"options": [
{
"id": 58,
"label": "cocoa",
"swatch_value": null,
"products": [
118
]
},
{
"id": 59,
"label": "dark chocolate",
"swatch_value": null,
"products": [
120,
127
]
},
{
"id": 60,
"label": "apple",
"swatch_value": null,
"products": [
121,
128
]
},
{
"id": 61,
"label": "milk",
"swatch_value": null,
"products": [
122
]
},
{
"id": 62,
"label": "coconut",
"swatch_value": null,
"products": [
130
]
},
{
"id": 65,
"label": "cherry",
"swatch_value": null,
"products": [
126
]
}
]
所以第一个列表将包含上面的 json,第二个列表包含下面等于某些 ID 的数字。
List<int> secondList = [58, 59, 60, 61];
现在,当我想通过将 secondList 与第一个列表的 ID 进行比较来生成一个新列表时,第三个列表是空的。
List thirdList = firstList.options.where((element) => secondList.contains(element.id)).toList();
【问题讨论】: