Im trying to loop through two object lists i have. below is the sample structure of those lists.
List<Model1> list1 = [ Model1(name: name1, isFavorite: true, amount: 1.0), Model1(name: name2, isFavorite: true, amount: 4.0), Model1(name: name3, isFavorite: true, amount: 5.0)];
List<Model2> list2 = [Model2(name: name01, isSubscribed: true, percentage: 1.0), Model2(name: name02, isSubscribed: false, percentage: 7.0), Model2(name: name03, isSubscribed: true, percentage: 3.0), Model2(name: name04, isSubscribed: true, percentage: 9.0),]
i' comparing name of each two lists. i want to see if list1 contains any item from list2 and add them to a new list. let's say only name1 = name01 and name2 = name02 then list3 = [Model1(name: name1, isFavorite: true, amount: 1.0), Model1(name: name2, isFavorite: true, amount: 4.0),] also to see when list1 is compared with list2 and list1 items that are not matched with list2 items add to another new list. then list4 = [Model1(name: name3, isFavorite: true, amount: 5.0)]
i've tried with the following function nested for loop but my loop does not work as expected. can anyone help me to figure out this?
for (Model1 itemI in list1) {
for (Model2 itemJ in list2) {
if (itemI.name == itemJ.name) {
list3.add(itemI);
break;
} else {
list4.add(itemI);
break;
}
}
}
CodePudding user response:
You can use this instead:
List<Model1> list3 = list1.where((e1) => list2.any((e2) => e1.name == e2.name)).toList();
List<Model1> list4 = list1.where((e) => !list3.contains(e)).toList();
CodePudding user response:
The ‘break’ code exit the loop when execute at first time. Remove it
CodePudding user response:
Break keyword is used to terminate the loops. So remove it.