【问题标题】:How can I remove duplicate list then get the latest ID?如何删除重复列表然后获取最新 ID?
【发布时间】:2021-03-05 18:50:25
【问题描述】:

我有这个List<Map>

[
  {msg_id: 1, from_id: 10, to_id: 20, text: 'Some text123'},
  {msg_id: 2, from_id: 20, to_id: 10, text: 'Some text321'},
  {msg_id: 3, from_id: 10, to_id: 20, text: 'Some text again'},
  {msg_id: 4, from_id: 5, to_id: 15, text: 'Hello World'},
  {msg_id: 5, from_id: 15, to_id: 5, text: 'Hello World'}
];

然后我需要通过msg_id 获得最后一条消息,使用不同的聊天室,如下所示:

[
  {msg_id: 3, from_id: 10, to_id: 20, text: 'Some text again'},
  {msg_id: 5, from_id: 15, to_id: 5, text: 'Hello World'}
];

我已经尝试过distinct()set(),但我仍然感到困惑。我该怎么办?

【问题讨论】:

  • 你认为这里有什么重复?
  • @D'Kayd 聊天室 by from_id 和 to_id

标签: list flutter dart duplicates chat


【解决方案1】:

由于您想要的是“按 chat_room_id 分组”,我们需要先从 from_id 和 to_id 生成它。我假设您的列表已经按 msg_id 排序。我通过在排序后加入 from_id 和 to_id 来生成 chat_room_id。之所以需要先排序是因为from_id 10,to_id 20和from_id 20,to_id 10是同一个聊天室。

  List<Map> data = [
    {"msg_id": 1, "from_id": 10, "to_id": 20, "text": 'Some text123'},
    {"msg_id": 2, "from_id": 20, "to_id": 10, "text": 'Some text321'},
    {"msg_id": 3, "from_id": 10, "to_id": 20, "text": 'Some text again'},
    {"msg_id": 4, "from_id": 5, "to_id": 15, "text": 'Hello World'},
    {"msg_id": 5, "from_id": 15, "to_id": 5, "text": 'Hello World'}
  ];
​
  Map<String, Map> perRoom = {};
​
  data.forEach((d) {
    // getting room id
    List<int> roomIdList = [d["from_id"], d["to_id"]];
    // need to be sorted since from_id 10, to_id 20 is the same room as from_id 20, to_id 10
    roomIdList.sort();
    String roomId = roomIdList.join('-');
    perRoom[roomId] = d;
  });
​
  // convert Map<String, Map> back into List<Map>
  List<Map> onlyLatest = perRoom.values.toList();
​
  print(onlyLatest);

on Dartpad

如果您的列表来自查询,我真的建议您在数据库中包含 chat_room_id,因为您可以使用 GROUP BY 之类的东西,避免从数据库中获取大量数据。

【讨论】:

  • 所以我们得到了String类型的房间ID?
  • @husainazkas 是的。我想不出另一种更适合这个的类型。当然,如何生成 room_id 取决于您。只需确保使两个方向(从 10 到 20 和从 20 到 10)生成相同的 room_id
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-06
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
相关资源
最近更新 更多