2015-02-13 8 views
5

Come ottenere l'indice di un'istanza in un elenco?DART: indexOf() in un elenco di istanze

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

Cosa dovrebbe 'pts.indexOf (25)' tornare? Il primo elemento dove 'x' o' y' è uguale a '25'? –

+0

Ciao !! Il primo elemento dove x è uguale a 25. –

+0

La risposta di Gunter è un ottimo modo per fare ciò che stai cercando ed è davvero la risposta corretta alla domanda che hai posto. Tuttavia, se stai facendo queste ricerche spesso potresti voler considerare di archiviare i punti in una Mappa cancellata dal valore x o y. Puoi ancora accedere a quella Mappa come una lista usando 'map.values' ma cercare un punto per x sarà molto più veloce (la risposta di Gunter è O (n) mentre una mappa troverà il Punto in O (log n)) . –

risposta

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

Grazie mille !! –