Reputation: 313
var firstList= [1,2,3,4,5];
var secondList= [3,5];
// compare result : 3,5
// return true
var firstList= [1,2,3,4,5];
var secondList= [6,7,8];
// compare result : null
// return false
How can I compare elements the two lists? If there is matching data in the two lists, return true. if there is no match, return false
Upvotes: 7
Views: 17029
Reputation: 965
Just following up on Josteve's answer - this returns a bool as requested in the question rather than a string as Josteve's snippet shows:
void main() {
var firstList= [1,2,3,4,5];
var secondList= [3,5];
var thirdList= [9,10];
//There IS an intersection
print("Second List: ${isIntersect(secondList, firstList)}");
//There is NO intersection
print("Third List: ${isIntersect(thirdList, firstList)}");
}
bool isIntersect(List listOne, List listTwo) {
return listOne.toSet().intersection(listTwo.toSet()).isNotEmpty;
}
Upvotes: 0
Reputation: 3
I found this works
bool bTest2 = lstPlayerIDPieceLocationPointID
.any((element) => lstFoundPoints.contains(element));
print('bTest2 any..contains: $bTest2');
Always finding if any item in 1 list is also in the other list. I did not care what is was, I just wanted to know if there is a match
Upvotes: 0
Reputation: 994
there is plenty of ways to do it, you could use every()
and contains()
methods to achieve this
this is how I would do it:
if (secondList.every((item) => firstList.contains(item))) {
return true;
} else {
return false;
}
Upvotes: 18
Reputation: 9859
Next solution is not perfect, but maybe helpful for someone:
void main() {
var list = ["aa", "bb", "cc"];
for (var el in ['abc', 'aaa', 'bb', 'hmbb', 'afg', 'hhcc']) {
bool isContains = list.any((e) => el.contains(e));
if(isContains) {
print(el);
}
}
}
Output:
aaa
bb
hmbb
hhcc
Upvotes: 2
Reputation: 12287
And one more quick way just to check true or false
var firstList = [2, 2, 2, 3];
var secondList = [3, 3, 3];
check(int value) => firstList.contains(value);
bool res = secondList.any(check); // returns true
Upvotes: 5
Reputation: 12673
This should help you...
var firstList = [2, 2, 2, 3];
var secondList = [3, 3, 3];
var firstListSet = firstList.toSet();
var secondListSet = secondList.toSet();
print(firstListSet.intersection(secondListSet));
Upvotes: 20