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.
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; });
}
You can just do
string item = "Car";
...
int itemId = list.FindIndex(a=>a == item);
string toLookFor = passedInString;
int boxId = list.FindIndex(new Predicate((s) => (s == toLookFor)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With