2009-06-12 10 views
7

それは私がリスト内のアイテムのIDを取得したい場合、私はこれを行うことができますというのが私の理解だ中で未定義の文字列のインデックスを見つけるにはどうすればよい:場合私はリスト<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"); 
} 

しかし、何を私は比較を動的にしたいですか?だからitem == "box"かどうかを調べるのではなく、ユーザーが入力した文字列をデリゲートに渡し、item == searchStringかどうかをチェックしたいと思います。

答えて

18

匿名メソッドまたはラムダによるコンパイラ生成クロージャを使用すると、述語式でカスタム値を使用することができます。

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

は、.NET 2.0(なしラムダ)を使用している場合、これは同様に動作します:

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

美しいを行うことができます仲間、ありがとう!私の3.0アップグレードを楽しみにして、私はそれらのラムダを使用することができます。 – ChristianLinnell

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

あなただけ

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; 
      } 
     } 
関連する問題