Home > database >  How to check and compare two different list
How to check and compare two different list

Time:02-26

I have 2 list:

  List<Users> users = List();
  List<String> allIds = List();

users.id has following data [1,2,3,4,9] and allIds has following data [12,1,2,3,4,5,6,7,8,9,90,50,20]

Now I want to know whether all data of users.id exist in allIds list or not.

CodePudding user response:

final allUsersID = users.every((Users u) => allIds.contains(u.id));

if (allUsersID) {
 print('all data of users.id EXIST in allIds list');
} else {
 print('all data of users.id DO NOT EXIST in allIds list!');
}

CodePudding user response:

Use this code:

List<String> ids=users.map((e) => e.id).tolist();
List<String> union=[...ids, ...allIds ].toSet().toList();
if(union.length==allIds.length)
{
   //all data of users.id exist in allIds
}

CodePudding user response:

Since there are two good answers I just want to add another solution. Remove all user's id from allIds then if the allIds is empty so 2 lists are equal.

 for (final user in users) {
   allIds.remove(user.id);
 }
 
 if (allIds.isEmpty) {
   // 2 lists are equal
 } else {
   // 2 lists are not equal and you can access all ids not found in your user's list
 }

CodePudding user response:

And here is a solution using Set class containsAll method:

allIds.toSet().containsAll(users.map((x) => x.id))
  • Related