2009-06-12 11 views
7

E 'la mia comprensione che se voglio ottenere l'ID di un elemento in una lista, posso fare questo:Come faccio a trovare l'indice di una stringa non definito in un elenco <T>

private static void a() 
{ 
    List<string> list = new List<string> {"Box", "Gate", "Car"}; 
    Predicate<string> predicate = new Predicate<string>(getBoxId); 
    int boxId = list.FindIndex(predicate); 
} 

private static bool getBoxId(string item) 
{ 
    return (item == "box"); 
} 

Ma cosa succede se Voglio rendere dinamico il confronto? Quindi, invece di controllare se item == "box", voglio passare una stringa inserita dall'utente al delegato e controllare se item == searchString.

risposta

18

L'utilizzo di una chiusura generata dal compilatore tramite un metodo anonimo o lambda è un buon metodo per utilizzare un valore personalizzato in un'espressione di predicato.

private static void findMyString(string str) 
{ 
    List<string> list = new List<string> {"Box", "Gate", "Car"}; 
    int boxId = list.FindIndex(s => s == str); 
} 

Se stai usando .NET 2.0 (senza lambda), questo funzionerà così:

private static void findMyString(string str) 
{ 
    List<string> list = new List<string> {"Box", "Gate", "Car"}; 
    int boxId = list.FindIndex(delegate (string s) { return s == str; }); 
} 
+0

Bella amico, grazie! Non vedo l'ora del mio aggiornamento 3.0, quindi posso usare quei lambda. – ChristianLinnell

1
string toLookFor = passedInString; 
int boxId = list.FindIndex(new Predicate((s) => (s == toLookFor))); 
2

Si può solo fare

string item = "Car"; 
... 

int itemId = list.FindIndex(a=>a == item); 
0
List <string> list= new List<string>("Box", "Gate", "Car"); 
string SearchStr ="Box"; 

    int BoxId= 0; 
     foreach (string SearchString in list) 
     { 
      if (str == SearchString) 
      { 
       BoxId= list.IndexOf(str); 
       break; 
      } 
     } 
Problemi correlati