【问题标题】:How to remove duplicate elements from a list using lists in Dart / Flutter?如何使用 Dart / Flutter 中的列表从列表中删除重复元素?
【发布时间】:2020-12-14 01:07:52
【问题描述】:

如何从 Dart / Flutter 中的列表中删除重复项?

.toSet().toList() 不起作用。

例如:

List one = [
     [
        [6, 51],
        [2, 76]
     ],
     [
        [6, 51],
        [2, 76]
     ],
     [
        [5, 66],
        [4, 96]
     ]
]

应该是:

List two = [
     [
        [6, 51],
        [2, 76]
     ],
     [
        [5, 66],
        [4, 96]
     ]
]

【问题讨论】:

    标签: arrays list flutter dart


    【解决方案1】:

    我希望这有效。同时导入'dart:convert';

    List two = 
      one.map((f) => f.toString()).toSet().toList()
      .map((f) => json.decode(f) as List<dynamic>).toList();
    

    【讨论】:

      【解决方案2】:

      效率不是很高,但这可以工作

      void main() {
        List<List<List<int>>> one = [
          [
            [6, 51],
            [2, 76]
          ],
          [
            [6, 51],
            [2, 76]
          ],
          [
            [5, 66],
            [4, 96]
          ]
        ];
      
        print(one);
      
        print(one.removeDuplicates());
      }
      
      extension ListExtension<T> on List<T> {
        bool _containsElement(T e) {
          for (T element in this) {
            if (element.toString().compareTo(e.toString()) == 0) return true;
          }
          return false;
        }
      
        List<T> removeDuplicates() {
          List<T> tempList = [];
      
          this.forEach((element) {
            if (!tempList._containsElement(element)) tempList.add(element);
          });
          
          return tempList;
        }
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-16
        • 1970-01-01
        • 2017-09-03
        • 1970-01-01
        • 1970-01-01
        • 2012-05-09
        • 1970-01-01
        • 2015-01-05
        相关资源
        最近更新 更多