DART: indexOf() in a list of Instances
Asked Answered
M

1

9

How to obtain the index of one Instance in a List?

class Points {
  int x, y;
  Point(this.x, this.y);
}

void main() {
  var pts = new List();
  int Lx;
  int Ly;

  Points pt = new Points(25,55); // new instance
  pts.add(pt);

  int index = pts.indexOf(25); // Problem !!! How to obtain the index in a list of instances ?
  if (index != -1 ){
  Lx = lp1.elementAt(index).x;
  Ly = lp1.elementAt(index).y;
  print('X=$Lx Y=$Ly');
}
Mirabel answered 13/2, 2015 at 13:47 Comment(3)
What should pts.indexOf(25) return? The first element where x or y equals 25?Resumption
Hi!! The first element where x equals 25.Menstrual
Gunter's answer is a great way to do what you are looking for, and is indeed the correct answer to the question you asked. However, if you are doing these lookups often you may want to consider storing the points in a Map keyed off the x or y value. You can still access that Map like a list using map.values but looking up a Point by x value would be much faster (Gunter's answer is O(n) whereas a map will find the Point in O(log n) time).Fortis
P
11
  // some helper to satisfy `firstWhere` when no element was found
  var dummy = new Point(null, null);
  var p = pts.firstWhere((e) => e.x == 25, orElse: () => dummy);
  if(p != dummy) {
    // don't know if this is still relevant to your question
    // the lines above already got the element 
    var lx = pts[pts.indexOf(p)];
    print('x: ${lx.x}, y: ${lx.y}');
  }
Professed answered 13/2, 2015 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.