Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

It's my understanding that if I want to get the ID of an item in a list, I can do this:

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.

like image 326
ChristianLinnell Avatar asked Jun 12 '09 04:06

ChristianLinnell


3 Answers

Using a compiler-generated closure via an anonymous method or lambda is a good way to use a custom value in a predicate expression.

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:

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; });
}
like image 95
Jonathan Rupp Avatar answered Nov 04 '22 08:11

Jonathan Rupp


You can just do

string item = "Car";
...

int itemId = list.FindIndex(a=>a == item);
like image 2
Jaime Avatar answered Nov 04 '22 07:11

Jaime


string toLookFor = passedInString;
int boxId = list.FindIndex(new Predicate((s) => (s == toLookFor)));
like image 1
Ana Betts Avatar answered Nov 04 '22 08:11

Ana Betts