【问题标题】:Generate 3rd list from adding two different lists通过添加两个不同的列表生成第三个列表
【发布时间】:2020-11-23 11:25:10
【问题描述】:

我有两个列表

List A have 3 items
List A={[name: abc, desc: abcd, img: httpsURL1],
       [name: xyz, desc: wxyz, img: httpsURL2],
       [name: def, desc: sahdw, img: httpsURL3]}

List B has only one item and name argument is same in both
List B={[name: abc, progress: 0.75]},

现在我想生成如下第三个列表:

List C = {[name: abc, desc: abcd, img: httpsURL1, progress:0.75],
       [name: xyz, desc: wxyz, img: httpsURL2, progress: 0],
       [name: def, desc: sahdw, img: httpsURL3, progress: 0]}

在 Dart 中可以吗?

【问题讨论】:

  • 当然可以,例如循环遍历较大的列表,如果键匹配则添加较小列表中的条目,否则添加默认值
  • 你能给我一些默认值的代码吗,
  • 我试过但出现索引问题
  • @iDecode 我有 3 个列表 List allData = HomeScreenState.listAllDataByDay;列出 progressData = HomeScreenState.progressDataListByDayAndDiseaseName;列出 cardAllData = List();
  • @ShahHaroon 在您提供的代码中,它们实际上是Set

标签: flutter dart


【解决方案1】:

我在这里做了一个假设,即第一个列表将始终包含所有元素。否则,这应该是您提供的输入的示例,并提供您期望的输出。

在 DartPad 中查看此示例: https://dartpad.dev/3cf607d4d0284702319e562099e19b1e

void main() {
  var aList = [
    new ClassA("abc", "abcd", "httpsURL1"),
    new ClassA("xyz", "wxyz", "httpsURL2"),
    new ClassA("def", "sahdw", "httpsURL3")
  ];

  var bList = [
    new ClassB("abc", 0.75),
  ];

  var result = aList
      .map((a) => bList.any((b) => b.name == a.name)
          ? new ClassC(a.name, a.desc, a.img,
              bList.firstWhere((b) => a.name == b.name).progress)
          : new ClassC(a.name, a.desc, a.img, 0))
      .toList();

  print(result);
}

class ClassA {
  String name;
  String desc;
  String img;

  ClassA(this.name, this.desc, this.img);
}

class ClassB {
  String name;
  double progress;

  ClassB(this.name, this.progress);
}

class ClassC {
  String name;
  String desc;
  String img;
  double progress;

  ClassC(this.name, this.desc, this.img, this.progress);
}

【讨论】:

  • 非常感谢你的朋友,我正是在找这个,谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-29
  • 1970-01-01
相关资源
最近更新 更多