gpt4 book ai didi

flutter - List> - 删除重复项但堆栈号

转载 作者:行者123 更新时间:2023-12-03 03:54:26 25 4
gpt4 key购买 nike

我希望有人可以帮助我。我试图通过保留相同的描述来获取对象列表并堆叠所有重复项,但在需要时增加数量。

这是我目前拥有的:

测试数据:

  List<Map<String, dynamic>> items = [
{'Description': 'Cheese', 'Quantity': 100, 'UoM': 'g'},
{'Description': 'Corn', 'Quantity': 150, 'UoM': 'g'},
{'Description': 'Cheese', 'Quantity': 52, 'UoM': 'g'},
];

我想弄清楚的功能:
  void stackDuplicates(items) {

final set = Set<String>();
int counter = 0;

// check the entire list only once
while (counter < items.length) {
items.forEach((item) {

// increase counter once a new item is checked
counter++;

// print the duplicate item for reference
//TODO: figure out how to check for duplicates without knowing the 'Description'
if (item.containsValue('Cheese')) {
print(item);
}

});

// return a list of unique descriptions
final newItems = items.where((item) {
return set.add(item['Description']);
}).toList();

// Print result
print(newItems);
}
}
}

stackDuplicates(items);

我似乎无法弄清楚如何将重复数量组合在一起制作一个新列表。
此外,我试图在不知道值是 Cheese 的情况下检查重复项;值(value)可以是任何东西。

任何帮助将不胜感激。

编辑:对不起,我忘了提,如果计量单位不同,请不要堆叠它们。

最佳答案

1) 堆叠到Map在哪里 keyDescription-UoM 组成字段

2) 如果 Map 中存在这样的 key 简单累积Quantity
3) 将 map 值作为列表返回

List<dynamic> stackDuplicates(items) {
Map<String, dynamic> uniqueItems = {};

for (Map item in items) {
final key = '${item["Description"]}-${item["UoM"]}';

(uniqueItems[key] == null)
? uniqueItems[key] = item
: uniqueItems[key]['Quantity'] += item['Quantity'];
}

return uniqueItems.values.toList();
}


List<Map<String, dynamic>> items = [
{'Description': 'Cheese', 'Quantity': 100, 'UoM': 'g'},
{'Description': 'Corn', 'Quantity': 150, 'UoM': 'g'},
{'Description': 'Cheese', 'Quantity': 52, 'UoM': 'g'},
];

final stackedItems = stackDuplicates(items);
print(stackedItems);

随时更改 key值取决于分组规则。

关于flutter - List<Map<String, dynamic>> - 删除重复项但堆栈号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61901680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com