How can I iterate through two lists in parallel in Dart?

Viewed 7678

I have two lists that I have confirmed are the same length. I want to operate on them at the same time. My code currently looks something like this:

var a = [1, 2, 3];
var b = [4, 5, 6];
var c = [];
for(int i = 0; i < a.length; i++) {
  c.add(new Foo(a, b));
}

It seems a bit clunky to count up to the length of list A in this fashion. Is there a nicer and more Dart-y way of accomplishing this task?

5 Answers

No need for external package, there's a built-in class IterableZip in the collections package:

import 'package:collection/collection.dart';

final a = [1, 2, 3];
final b = [4, 5, 6];
List<Foo> c = [];
for (final pairs in IterableZip([a, b])) {
  c.add(Foo(pairs[0], pairs[1]));
}

Some more notes:

  • package:collection/iterable_zip.dart is deprecated, you'd need to import simply the collection.dart like shown.
  • final a and final b variables will have inferred template list types. I have not specified template type for IterableZip, but in some cases (in a complex case where I used it) you may need to explicitly type it like IterableZip<int>, so in the loop you can more conveniently access the members. In this simple case the compiler/interpreter can infer the type easily.

Now that we have list comprehensions in dart:

final c = [for(int i = 0; i<a.length; i+= 1) Foo(a[i], b[i])];

If you want an even shorter solution using the quiver package's zip function, you can do the following:

final c = zip([a, b]).map((item) => Foo(item[0], item[1])).toList();
var c = List.generate(a.length, (i) => Foo(a[i], b[i]));
Related