Reputation: 1883
I have a scenario where I want to perform an action if a string in a list of string matches the index in a list of ints (Generated based on String list )
The below is some pseudo code to try and articulate what I am trying to achieve.
List<int> wordIndex = [1,3,5];
List<String> wordList = ['this', 'is','a', 'test', 'a'];
//Pseudo code
wordList.forEach(word)) {
if (wordIndex item matches index of word) {
do something;
} else {
od something else;
}
}
it the if (wordIndex item matches index of word)
where I am having a problem and would appreciate any ideas.
Upvotes: 1
Views: 76
Reputation: 126624
If I understand you correctly, you want to know if the index of a word is contained in you wordIndex
list, i.e. you want to get all wordList
items with an index that is stored in wordIndex
.
There are two approaches to this:
Iterable.contains
In this case, we are simple checking if the current index is present in the wordIndex
list.
for (var index = 0; index < wordList.length; index++) {
if (wordIndex.contains(index)) {
// do something
return;
}
// do something else
}
wordIndex
If you are just interested in the matching items, this approach is more reasonable.
Here, we loop through the index list and then simply get the matching elements in the wordList
. However, you will not be able to take actions for the non-matching items:
for (final index in wordIndex) {
final word = wordList[index];
// do something
}
Upvotes: 0
Reputation: 7921
Just use for
instead of forEach
;
List<int> wordIndex = [1,3,5];
List<String> wordList = ['this', 'is','a', 'test', 'a'];
//Pseudo code
for (int i = 0; i < wordList.length; i++) {
if (wordIndex.contains(i)) {
do something;
} else {
od something else;
}
}
Upvotes: 1