Home > Software design >  Iterating over maps in List and matching value in Dart
Iterating over maps in List and matching value in Dart

Time:04-21

please help with code to print value of key c by comparing key value of a and b

the output should be 29

int a = 3;
int b = 6;

List nums = [
  {'a': 1, 'b': 6, 'c': 9},
  {'a': 1, 'b': 7, 'c': 10},
  {'a': 3, 'b': 8, 'c': 19},
  {'a': 3, 'b': 6, 'c': 29},
  {'a': 2, 'b': 7, 'c': 39},
  {'a': 2, 'b': 8, 'c': 49},
];

CodePudding user response:

As per https://api.dart.dev/stable/2.16.2/dart-core/Iterable/where.html

    void main() {
      
      int a = 3;
    int b = 6;
    
    List nums = [
      {'a': 1, 'b': 6, 'c': 9},
      {'a': 1, 'b': 7, 'c': 10},
      {'a': 3, 'b': 8, 'c': 19},
      {'a': 3, 'b': 6, 'c': 29},
      {'a': 2, 'b': 7, 'c': 39},
      {'a': 2, 'b': 8, 'c': 49},
    ];
      
      
     
        print(nums.where((m) => m['a'] == a && m['b'] == b));

print(nums.where((m) => m['a'] == a && m['b'] == b).elementAt(0)['c']);
     
    }

the output will be

({a: 3, b: 6, c: 29})

29

CodePudding user response:

The following code will output 29.

main(){
  int a = 3;
  int b = 6;

  List nums = [
    {'a': 1, 'b': 6, 'c': 9},
    {'a': 1, 'b': 7, 'c': 10},
    {'a': 3, 'b': 8, 'c': 19},
    {'a': 3, 'b': 6, 'c': 29},
    {'a': 2, 'b': 7, 'c': 39},
    {'a': 2, 'b': 8, 'c': 49},
  ];

  for(var item in nums){
    if(item['a'] == a && item['b'] == b){
      print(item['c']); // => 29
    }
  }
}
  • Related