NullifyNetwork

The blog and home page of Simon Soanes
Skip to content
[ Log On ]

This is just a quick example so I don't forget how to search generic lists easily and have to hunt for it again, but I've fleshed it out so it will hopefully be of help to someone else!

//Set up our example generic List
List<string> myItems = new List<string>();
myItems.Add("This isn't going to be found");
myItems.Add("Nor this");
myItems.Add("But it will find this example for nullify!");
myItems.Add("And it will find this nullify example too!");
//This is our search term, it is a local variable
string localVariable = "nullify";

//Do the search using a Predicate<> delegate here.
//
//This can point to a method that takes a parameter of the type, but
//doing that will result in not being able to pass parameters to the
//method (its parameters are predefined as the type, with a boolean
//return as far as I can see). We get around this by using an
//anonymous delegate, so it is inline and can access local variables

string[] matches = myItems.FindAll(delegate(string searchItem) {
    //this is an anonymous delegate, that
    return searchItem.IndexOf(localVariable)>-1;
}).ToArray();

 

Updated 7/2/2010: You could also use a Lambda expression to do this with a few less characters:-

string[] matches = myItems.FindAll(searchItem => {
    //this is an anonymous delegate, that 
    return searchItem.IndexOf(localVariable)>-1; 
}).ToArray();

Permalink