DART:在实例列表中使用indexOf()函数

9
如何在列表中获取一个实例的索引?
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');
}

pts.indexOf(25) 应该返回什么?第一个元素是 xy 等于 25 吗? - Günter Zöchbauer
嗨! x等于25时的第一个元素。 - Gúbio Bonner
Gunter的回答是您正在寻找的一个很好的方法,也确实是您提出的问题的正确答案。但是,如果您经常进行这些查找,您可能需要考虑将点存储在以x或y值为键的Map中。您仍然可以像使用map.values一样访问该Map,但通过x值查找Point会更快(Gunter的答案是O(n),而Map将在O(log n)时间内找到Point)。 - Michael Fenwick
1个回答

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}');
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接