list 有没有一种简单的方法可以在 Dart 中组合两个列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21826342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 02:08:48  来源:igfitidea点击:

Is there a simple way to combine two lists in Dart?

listgenericsdart

提问by Alex

I was wondering if there was an easy way to combine two lists in dart to create a brand new list object. I couldn't find anything and something like this:

我想知道是否有一种简单的方法可以在 dart 中组合两个列表来创建一个全新的列表对象。我找不到任何类似的东西:

var newList = list1 + list2;

Isn't valid.

无效。

回答by Alexandre Ardhuin

You can use:

您可以使用:

var newList = new List.from(list1)..addAll(list2);

If you have several lists you can use:

如果您有多个列表,则可以使用:

var newList = [list1, list2, list3].expand((x) => x).toList()

As of Dart 2 you can now use +:

从 Dart 2 开始,您现在可以使用+

var newList = list1 + list2 + list3;

As of Dart 2.3 you can use the spread operator:

从 Dart 2.3 开始,您可以使用扩展运算符:

var newList = [...list1, ...list2, ...list3];

回答by Ticore Shih

maybe more consistent~

也许更一致~

var list = []..addAll(list1)..addAll(list2);

回答by Daniel Robinson

Alexandres' answer is the best but if you wanted to use + like in your example you can use Darts operator overloading:

Alexandres 的答案是最好的,但是如果您想在示例中使用 + like,您可以使用 Darts 运算符重载:

class MyList<T>{
  List<T> _internal = new List<T>();
  operator +(other) => new List<T>.from(_internal)..addAll(other);
  noSuchMethod(inv){
    //pass all calls to _internal
  }
}

Then:

然后:

var newMyList = myList1 + myList2;

Is valid :)

已验证 :)

回答by Erlend

Dart now supportsconcatenation of lists using the +operator.

Dart 现在支持使用+运算符连接列表。

Example:

例子:

List<int> result = [0, 1, 2] + [3, 4, 5];

回答by Nuts

If you want to merge two lists and remove duplicates could do:

如果要合并两个列表并删除重复项可以执行以下操作:

var newList = [...list1, ...list2].toSet().toList();