C# articles and tutorials on SharpDeveloper.NET

Sharpen your .NET skills with our C# articles, tutorials, demos, and source code by Sameer Alibhai
posts - 63, comments - 53, trackbacks - 1

.NET Predicates (and a .RemoveAll() example)

A predicate is a function that returns true or false and can be used for example to filter your results.. For example your .NET RemoveAll(...) function can actually do things like:

Remove all records that say ...

  • "start with S"
  • or "are 5 letters long"
  • etc etc..
  • whatever you wanna do.. GO WILD!

And knowing this, plus using our .NET 2.0 anonymous methods, we can do the above filtering in a single line!  We don't even need to write a special predicate function.

For example if you have a general list of ints, and you want to remove all ints that are equal to the value 5, you can do the following:

yourList.RemoveAll(new System.Predicate<int>( delegate(int val) { return (val == 5); })); 
The keyword delegate(int val) { ... } allows you to create an anonymous method.

Follow Up


Print | posted on Friday, May 25, 2007 12:35 PM | Filed Under [ .NET articles ]

Feedback

Gravatar

# re: .NET Predicates (and a .RemoveAll() example)

kewl
8/14/2008 3:14 PM | Kudzu Fire

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 5 and 2 and type the answer here:

Powered by: