C# 如何在 List<T> 中找到未定义字符串的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/984982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find the index of an undefined string in a List<T>
提问by ChristianLinnell
It's my understanding that if I want to get the ID of an item in a list, I can do this:
我的理解是,如果我想获取列表中项目的 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");
}
But what if I want to make the comparison dynamic? So instead of checking if item=="box", I want to pass in a user-entered string to the delegate, and check if item==searchString.
但是如果我想让比较动态呢?因此,我不想检查 item=="box",而是将用户输入的字符串传递给委托,并检查 item==searchString.
采纳答案by Jonathan Rupp
Using a compiler-generated closure via an anonymous method or lambda is a good way to use a custom value in a predicate expression.
通过匿名方法或 lambda 使用编译器生成的闭包是在谓词表达式中使用自定义值的好方法。
private static void findMyString(string str)
{
List<string> list = new List<string> {"Box", "Gate", "Car"};
int boxId = list.FindIndex(s => s == str);
}
If you're using .NET 2.0 (no lambda), this will work as well:
如果您使用 .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; });
}
回答by Ana Betts
string toLookFor = passedInString;
int boxId = list.FindIndex(new Predicate((s) => (s == toLookFor)));
回答by Jaime
You can just do
你可以做
string item = "Car";
...
int itemId = list.FindIndex(a=>a == item);
回答by Vijay Mungara
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;
}
}