views:

1662

answers:

3

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.

+6  A: 

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; });
}
Jonathan
Beautiful mate, thanks! Looking forward to my 3.0 upgrade so I can use those lambdas.
ChristianLinnell
A: 

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

Paul Betts
A: 

You can just do

string item = "Car";
...

int itemId = list.FindIndex(a=>a == item);
Jaime