簡體   English   中英

如何在List中找到未定義字符串的索引<T>

[英]How do I find the index of an undefined string in a List<T>

我的理解是,如果我想獲取列表中項目的ID,我可以這樣做:

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。

通過匿名方法或lambda使用編譯器生成的閉包是在謂詞表達式中使用自定義值的好方法。

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(沒有lambda),那么它也會起作用:

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

你可以這樣做

string item = "Car";
...

int itemId = list.FindIndex(a=>a == item);
string toLookFor = passedInString;
int boxId = list.FindIndex(new Predicate((s) => (s == toLookFor)));
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;
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM