作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想从列表中删除一个对象,但是看不到。
我想删除具有相同类型的对象,并按类型保持最大距离。
这是我的代码:
int userDistance = 851;
final String chargesJson = '''[
{
"type" : 1,
"distance": 800,
"setting": 1122,
"bond" : 44
},
{
"type" : 1,
"distance": 850,
"setting": 1076,
"bond" : 50
},
{
"type" : 2,
"distance": 800,
"setting": 1336,
"bond" : 37
},
{
"type" : 2,
"distance": 900,
"setting": 1299,
"bond" : 39
}
]
''';
final List charges = json.decode(chargesJson);
Map searchCharges(int userDistance) {
Map result = {};
// List all charges that are less than userDistance
// Remove all charges that are higher
List positiveDistanceDiff = charges.where((c) => userDistance - c['distance'] >= 0 ).toList();
print('positiveDistanceDiff : $positiveDistanceDiff');
positiveDistanceDiff : [{type: 1, distance: 800, setting: 1122, bond: 44}, {type: 1, distance: 850, setting: 1076, bond: 50}, {type: 2, distance: 800, setting: 1336, bond: 37}]
{type: 1, distance: 800, setting: 1122, bond: 44}
最佳答案
像这样吗我不确定我是否完全理解您的问题,因为按照您自己的逻辑,您还应该删除距离为800的“type:2”条目?
另外,我编写了代码,因此它创建了一个新列表,其中的值已被过滤。
import 'dart:convert';
const String chargesJson = '''[
{
"type" : 1,
"distance": 800,
"setting": 1122,
"bond" : 44
},
{
"type" : 1,
"distance": 850,
"setting": 1076,
"bond" : 50
},
{
"type" : 2,
"distance": 800,
"setting": 1336,
"bond" : 37
},
{
"type" : 2,
"distance": 900,
"setting": 1299,
"bond" : 39
}
]
''';
void main() {
final charges = json.decode(chargesJson) as List<dynamic>;
final filteredList = charges
.cast<Map<String, dynamic>>()
.fold(<int, Map<String, dynamic>>{},
(Map<int, Map<String, dynamic>> map, element) {
final type = element['type'] as int;
if (!map.containsKey(type) ||
(map[type]['distance'] as int) < (element['distance'] as int)) {
map[type] = element;
}
return map;
})
.values
.toList();
filteredList.forEach(print);
// {type: 1, distance: 850, setting: 1076, bond: 50}
// {type: 2, distance: 900, setting: 1299, bond: 39}
}
关于dart - Dart移除 list 中的 object ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62376992/
我正在做一个项目,我的 android 在这个项目中作为一个网络服务器工作;输入带端口号的 IP 地址,打开 Web 界面,用户可以将文件上传到手机。我想在 Web 界面上显示一些图片,以便我们的界面
我是一名优秀的程序员,十分优秀!