如何检查列表中是否已经存在字符串? [英] How to check if string already exists in list?

查看:42
本文介绍了如何检查列表中是否已经存在字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从firebase创建具有数组的字符串列表.而且效果很好.但是现在我想过滤一下名单.所以我想要的是一次性添加allhastags.因此,如果主题标签存在两次,我只想将其放入列表中一次即可.这是我的代码

Im trying to create a list of string which has array from firebase . And that works perfectly. But now I wanna filter the list a bit . So what I want is add allhastags one time . So if a hashtags exist twice I wanna just put it int he list once. Heres my code


  Future<List<String>> getHashtags() async {
    List<String> allVideoHastags = [];

    QuerySnapshot snapshots =
        await FirebaseFirestore.instance.collection('videos').get();

    for (QueryDocumentSnapshot videoSnapshot in snapshots.docs) {
      List<String> videoHastags =
          List.from(videoSnapshot.data()['Hashtagsforallvideos']);
      allVideoHastags.addAll(videoHastags);
    }
    _allResults = allVideoHastags;
     searchResults();
   
    return allVideoHastags;
  }

因此,在将主题标签添加到列表之前,我想检查字符串列表中是否已经存在.希望任何人都可以提供帮助.如果您需要更多信息,请发表评论

So before adding the hashtags into the list ,I wanna check if it already exists in the list of strings .Hope anyone can help .If you need more information please leave a comment

推荐答案

仅循环遍历从firebase中获得的主题标签,然后仅将其添加到结果中(如果它们还没有在其中):

Just loop over the hashtags you get from firebase and add them to your results only if they are not already in there like this:

Future<List<String>> getHashtags() async {
  List<String> allVideoHastags = [];

  QuerySnapshot snapshots =
      await FirebaseFirestore.instance.collection('videos').get();

  for (QueryDocumentSnapshot videoSnapshot in snapshots.docs) {
    List<String> videoHastags =
        List.from(videoSnapshot.data()['Hashtagsforallvideos']);

    videoHastags.forEach((element) {
      if(!allVideoHastags.contains(element)){
          allVideoHastags.add(element);
      }
    });
    
  }
  _allResults = allVideoHastags;
  searchResults();

  return allVideoHastags;
}

这篇关于如何检查列表中是否已经存在字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆