Predicate with Example : C#

Introduction

When we want to test some criteria on collection object’s element and depending upon result test result (true or false) we perform some operation on that collection or its elements, we should use predicate.

From MSDN:

Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.

Predicate<T> is a functional construct providing a convenient way of basically testing if something is true of a given T object.

Example

For example suppose we have to find all even number from list, we do like:

Or with help of lambdas expression we can do like:

Another Example

Suppose we have a class

Now let’s say I have a List employees and I want to know if there’s anyone named “Ajay” in the list.

Without using a Predicate, I always perform this as below:

This is fine, but then we want to check if there’s a employee named “Saurav”? Or a employee whose id is 101?

Using a Predicate, we can find these things using a LOT less code:

Using even write short code for predicate using lambdas expression:

I hope that you have now better understanding of Predicate.

Please leave a comment, it encourage me to write quality articles.

Happy reading and Coding 🙂

Advertisements

One thought on “Predicate with Example : C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s