0

I'm trying to find a nice way to determine if all items in one list exist in another list.

I have tried various methods, but they get uglier and uglier as I go and I'm hoping there is an elegant solution out there somewhere.

Attempt 1:

if (listOne.contains(ListTwo)) 

This doesn't error, but also doesn't work. I assume it is looking to find not the items but the actual list which it wont.

Attempt 2:

if (listOne.toString().substring(1,listOne.toString().length - 1).contains(listTwo.toString().substring(1,listTwo.toString().length - 1))) 

This actually works, but it just seems fragile to me

Question: What is an elegant solution to determine if all the items in one list are in another list?

Yonkee
  • 1,781
  • 3
  • 31
  • 56
  • Does this answer your question? [How can I compare Lists for equality in Dart?](https://stackoverflow.com/questions/10404516/how-can-i-compare-lists-for-equality-in-dart) – i6x86 Mar 27 '20 at 05:33
  • 2
    `var one = [1,3,4,6,8,9]; var two = [6]; print(one.toSet().containsAll(two));` – pskink Mar 27 '20 at 06:28
  • @pskink Perfect, thank again. Did you want to post this as an answer? – Yonkee Mar 28 '20 at 02:01

2 Answers2

1
main() {
 List<String> list1 = ["item1", "item2", "item3", "item4", "item5"];
  List<String> list2 = ["item2", "item1"];

  if (containsAll(list1, list2)) {
    print("it contains all");
  } else {
    print("it doesn't contain all");
  }
}

bool containsAll(List<dynamic> checkWhere, List<dynamic> checkWhich) {
  checkWhere.sort((a, b) => a.compareTo(b));
  checkWhich.sort((a, b) => a.compareTo(b));

  for (int i = 0; i < checkWhich.length; i++) {
    print(checkWhich.length);
    if (checkWhich[i] != checkWhere[i]) {
      return false;
    }
  }
  return true;
}
user3555371
  • 238
  • 1
  • 7
1

use this one-liner (i assume that lists dont care about the duplicated items):

print(listOne.toSet().containsAll(listTwo));
pskink
  • 23,874
  • 6
  • 66
  • 77