【问题标题】:Remove duplicate entries in a list删除列表中的重复条目
【发布时间】:2022-02-07 13:50:40
【问题描述】:

我有这些数据:

[
  { "name": "Eric", "origin": "Tristan da Cunha" },
  { "name": "Eric", "origin": "Tristan da Cunha" },
  { "name": "Adelaide", "origin": "Cayman Islands" }
]

有重复数据,如何在转换为列表之前将其删除?

【问题讨论】:

标签: flutter dart


【解决方案1】:

首先,为数据创建一个,包括hashCodeoperator 覆盖。 toString override 是可选的,但会有所帮助:

class DataModel {
  String? name;
  String? origin;

  DataModel({this.name, this.origin});

  @override
  int get hashCode => '$name, $origin'.hashCode;

  // this will do the magic
  @override
  bool operator ==(Object other) {
    return other is DataModel &&
        name.toString() == other.name.toString() &&
        origin.toString() == other.origin.toString();
  }

  @override
  String toString() {
    return "{name: '$name', origin: '$origin'}";
  }
}

然后,在你的 Dart 代码中的任何地方:

import 'data_model.dart';

void main(List<String> arguments) {
  // notice that Eric is duplicated in this entry
  List<DataModel> filterData = [
    DataModel(name: 'Eric', origin: "Tristan da Cunha"),
    DataModel(name: 'Eric', origin: "Tristan da Cunha"),
    DataModel(name: 'Adelaide', origin: "Cayman Islands"),
  ];

  // toSet() will remove the redundancy, then convert it back to toList()
  var removedDuplicatedDatas = filterData.toSet().toList();
  print(removedDuplicatedDatas);
}

输出:

[{name: 'Eric', origin: 'Tristan da Cunha'}, {name: 'Adelaide', origin: 'Cayman Islands'}]

【讨论】:

    【解决方案2】:

    按名称删除项目

     final ids = uniqueLedgerList.map((e) => e["name"]).toSet();
     uniqueLedgerList.retainWhere((x) => ids.remove(x["name"]));
                                                
     log("Remove Duplicate Items--->$uniqueLedgerList");
    

    【讨论】:

      猜你喜欢
      • 2013-03-09
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 2012-03-20
      • 2014-12-28
      • 2020-06-16
      • 1970-01-01
      • 2021-08-20
      相关资源
      最近更新 更多