You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart中如何参照另一列表的元素顺序对目标列表重排序

Dart 实现按自定义客户序列重排销售列表

核心实现逻辑:先基于用户调整好顺序的客户列表生成优先级映射,排序时直接比对每条销售记录对应客户的优先级值即可,同一客户下的销售ID顺序不做额外约束。

实现步骤

  • 遍历自定义排序的客户列表List2,生成客户名称:排序优先级的映射,优先级取元素在List2中的下标,下标越小排序越靠前
  • 调用原始列表List1的内置sort()方法,对比两条记录所属客户的优先级完成排序

完整可运行代码

void main() {
  // 原始销售数据List1
  final List<Map<String, String>> list1 = [
    {'CustomerName': 'StoreA', 'SalesId': '001'},
    {'CustomerName': 'StoreB', 'SalesId': '002'},
    {'CustomerName': 'StoreB', 'SalesId': '003'},
    {'CustomerName': 'StoreC', 'SalesId': '004'},
  ];

  // 用户调整顺序后的去重客户列表List2
  final List<String> list2 = ['StoreB', 'StoreC', 'StoreA'];

  // 构造客户优先级映射
  final Map<String, int> customerPriority = {
    for (int idx = 0; idx < list2.length; idx++) list2[idx]: idx
  };

  // 执行排序
  list1.sort((recordA, recordB) {
    // 若存在List2未收录的客户,可设置兜底优先级(如999)统一放到列表末尾
    final priorityA = customerPriority[recordA['CustomerName']] ?? 999;
    final priorityB = customerPriority[recordB['CustomerName']] ?? 999;
    return priorityA.compareTo(priorityB);
  });

  // 打印结果验证
  for (final item in list1) {
    print('${item['CustomerName']} - ${item['SalesId']}');
  }
}

运行输出

StoreB - 002
StoreB - 003
StoreC - 004
StoreA - 001

提示:如果你的销售数据是通过自定义类存储的,只需要将排序逻辑中取客户名称的部分替换为对应类的属性访问即可,核心排序逻辑不需要改动。

内容的提问来源于stack exchange,提问作者Toxic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 23:24:24