0

我有一个unfilteredList包含 12 项(消息)的列表。如输出所示,其中 9 条消息具有相同的roomID. 那么我的问题是:如何过滤掉这 9 个项目中的 8 个,这样我的列表 ,result每个只有 1 个roomIDs

我试图弄乱 for 循环并在roomID遇到一秒钟时删除一个项目。但似乎无法让它工作,我做错了什么?

List <Inbox> result = [];
int count = 0;
for(int i = 0; i < unfilteredList.length; i++){

  print(i.toString() + '. roomID: ' + unfilteredList[i].roomId);

  result.add(blah[i]);

  for(int j = 0; j < result.length; j++){
    if(result[j].roomId == unfilteredList[i].roomId){
      count++;
      if(count > 1){
        result.removeLast();
        count--;
      }
    }
  }
}

打印输出:

I/flutter (15029): 0. roomID: 1206f5058913246b47f898e7ab7e41ad
I/flutter (15029): 1. roomID: 15b08ee59f29b43d21a24ea6d4071b19
I/flutter (15029): 2. roomID: cd674af0f6048af49bf8222f24bd6103
I/flutter (15029): 3. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 4. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 5. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 6. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 7. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 8. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 9. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 10. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 11. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 12. roomID: f3f1e4385b36cdd04e10e776220b892e
4

3 回答 3

1

您可以使用 aSet来存储唯一的roomIds. 每次将新 id 添加到集合时,如果集合已包含它,则将其从结果列表中删除。

final uniqueIds = Set<String>();
result.removeWhere((item) => !uniqueIds.add(item.roomId));
于 2020-08-27T15:29:12.927 回答
0

使用 toSet(),然后使用 toList()。

final uniqueList = results.toSet().toList();
于 2020-08-27T14:49:00.277 回答
0

Well you can just check for the id with .contains() see an output from one of my apps as example:

for (var idx = 0; idx < sampleList.length; idx++){
      if(result.contains(sampleList[idx].userId)){
        print('id exists');
      } else {
        result.add(sampleList[idx].userId);
      }    
    }

It would add the id e5e210a53a3c7e1b03d6cbedbc9da786 the first time and after that skip it.

于 2020-08-27T12:23:22.823 回答