2015-02-13 9 views
5

Wie erhält man den Index einer Instanz in einer Liste?DART: indexOf() in einer Liste von Instanzen

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

Was soll 'pts.indexOf (25)' zurückkehren? Das erste Element, bei dem "x" oder "y" gleich "25" ist? –

+0

Hallo !! Das erste Element, in dem x gleich 25 ist. –

+0

Gunters Antwort ist eine gute Möglichkeit, das zu tun, was Sie suchen, und ist in der Tat die richtige Antwort auf die Frage, die Sie gestellt haben. Wenn Sie diese Suchvorgänge jedoch häufig durchführen, sollten Sie in Betracht ziehen, die Punkte in einer Map außerhalb des x- oder y-Werts zu speichern. Mit map.values ​​können Sie immer noch auf diese Map wie eine Liste zugreifen, aber ein Point by x Wert wäre viel schneller (Gunters Antwort ist O (n), während eine Map den Point in O (log n) Zeit findet) . –

Antwort

6
// 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}'); 
    } 
+1

Vielen Dank !! –