How do I combine two lists in Dart?

前端 未结 8 727
有刺的猬
有刺的猬 2021-01-31 00:46

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

My list:

相关标签:
8条回答
  • 2021-01-31 01:28

    Dart now supports concatenation of lists using the + operator.

    Example:

    List<int> result = [0, 1, 2] + [3, 4, 5];
    
    0 讨论(0)
  • 2021-01-31 01:38

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

    var newList = [...list1, ...list2].toSet().toList(); 
    
    0 讨论(0)
  • 2021-01-31 01:40

    We can add all the elements of the other list to the existing list by the use of addAll() method.

    Using addAll() method to add all the elements of another list to the existing list. and Appends all objects of iterable to the end of this list.

    Extends the length of the list by the number of objects in iterable. Throws an UnsupportedError if this list is fixed-length.

    Creating lists

    listone = [1,2,3]
    listtwo = [4,5,6]
    

    Combining lists

     listone.addAll(listtwo);
    

    Output:

    [1,2,3,4,5,6]
    
    0 讨论(0)
  • 2021-01-31 01:42

    maybe more consistent~

    var list = []..addAll(list1)..addAll(list2);
    
    0 讨论(0)
  • 2021-01-31 01:44

    addAll is the most common way to merge two lists.

    But to concatenate list of lists, you can use any of these three functions (examples below):

    • expand - Expands each element of an Iterable into zero or more elements,
    • fold - Reduces a collection to a single value by iteratively combining each element of the collection with an existing value,
    • reduce - Reduces a collection to a single value by iteratively combining elements of the collection using the provided function.
    void main() {
      List<int> a = [1,2,3];
      List<int> b = [4,5];
      List<int> c = [6];
      List<List<int>> abc = [a,b,c]; // list of lists: [ [1,2,3], [4,5], [6] ]
      List<int> ints = abc.expand((x) => x).toList();
      List<int> ints2 = abc.reduce((list1,list2) => list1 + list2);
      List<int> ints3 = abc.fold([], (prev, curr) => prev + curr); // initial value is []
      print(ints);  // [1,2,3,4,5,6]
      print(ints2); // [1,2,3,4,5,6]
      print(ints3); // [1,2,3,4,5,6]
    }
    
    0 讨论(0)
  • 2021-01-31 01:46

    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 +:

    var newList = list1 + list2 + list3;
    

    As of Dart 2.3 you can use the spread operator:

    var newList = [...list1, ...list2, ...list3];
    
    0 讨论(0)
提交回复
热议问题