如何在Dart中将两个列表相等并包含相同的对象? [英] How do I compare two lists as being equal and containing the same objects, in Dart?

查看:2160
本文介绍了如何在Dart中将两个列表相等并包含相同的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:

List fruits = ['apples', 'bananas'];
List foods = ['apples', 'bananas'];

如何比较水果和食物,并确保两个列表以相同的顺序具有相同的对象?

How can I compare fruits and foods and ensure that both lists have the same objects in the same order?

推荐答案

比较列表的相等性(而不是标识)的推荐方法是使用以下包中的Equality类



The recommended way to compare lists for equality (rather than identity) is by using the Equality classes from the following package

import 'package:collection/equality.dart';

例如,

Function eq = const ListEquality().equals;
print(eq(fruits, foods)); // => true

这适用于您的情况,因为 fruits foods 包含相应的参数 identical()。如果你想(深入地)比较可能包含其他集合的列表,请改用:

This works for your case because the fruits and foods contain corresponding arguments that are identical(). If you want to (deeply) compare lists that might contain other collections then instead use:

Function deepEq = const DeepCollectionEquality().equals;
List list1 = [1, ['a',[]], 3];
List list2 = [1, ['a',[]], 3];
print(    eq(list1, list2)); // => false
print(deepEq(list1, list2)); // => true

还有其他Equality类可以通过多种方式组合,包括 Map s。您甚至可以对集合执行无序(深层)比较:

There are other Equality classes that can be combined in many ways, including equality for Maps. You can even perform an unordered (deep) comparison of collections:

Function deepEq = const DeepCollectionEquality.unordered().equals;

有关详情,请参阅 package API documentation 。像往常一样,要使用这样的包,必须在 pubspec.yaml 中列出:

For details see the package API documentation. As usual, to use such a package you must list it in your pubspec.yaml:

dependencies:
  collection: any

这篇关于如何在Dart中将两个列表相等并包含相同的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆