Predicates, Converters and Actions

Friday, 27 July 2007 12:07 by admin

It's been a while that I blogged some serious (technical) stuff here. So I guess it's time again for another tips and tricks on C# that this blog supposedly offers.

What I'm going to share to you now is somewhat a shorthand of doing a basic looping routine using delegates and generics. Have you ever coded a routine that passes through all of your items in an array or a list and perform an operation per item? Are you getting tired of doing the same old stuff (for-each and for loops)? Well if you are, then this blog is for you.

Doing a loop within your array and doing an operation per item is a pretty much simple thing to do. You can call me lazy, but as you are doing this repetitively you often grow tired of seeing a single for loop statement. This prompted me to search the .net framework for some useful stuffs that might spice up my development. Hence I came across Predicates, Converters and Actions.

Predicates

A Predicate is a delegate located in the System Namespace which can be used as a determinant if the item within your array or list meets a specific condition or not.

Here's a simple example:

Suppose you have an array of integers and you want to get only the numbers that are greater that 5. Normally you will be doing this:

int[] arr = new int[] { 1,2,3,4,5,6,7,8,9,0 };
for (int i = 0; i < arr.Length; i++) {
    if (arr[i] > 5) {
       resArr[newIndex] = arr[i];
       newIndex++;
    }
}
/* I know the code is quite lame but I guess you know the idea */

You can convert it to this, by using a predicate:

bool Match(int item) {
    if (item > 5) {
        return true;
    } else {
        return false;
    }
}

// some code here...

Predicate<int> matchDelegate = new Predicate<int>(Match);
int[] resultArr = Array.FindAll<int>(_myIntArray, matchDelegate);

As you can see, we didn't even use a single for loop statement. This is done automatically upon calling the FindAll method of the Array class. This can also be applied to a List class as we can see in our next example.

 

Converters

A Converter is a delegate that is used to convert an item in an Array or List from one type to another.

Supposedly you have a List that contains integers and you want to convert all item to a string and store it in another List.

string converter(int item) {
    return item.ToString();
}

List<int> _listOfInt = new List<int>();
Converter<int, string> _converter = new Converter<int, string>(converter);

// Code to add each items goes here

List<string> _listOfString = _listOfInt.ConvertAll<string>(_converter);

The sample automatically converts all values in the List to string.

Actions

An Action is a delegate that specifies a routine that will be executed during the looping of the List.

Suppose you want to display all values of the List to the Debug Window. So instead of creating a loop, you can use Actions to do that.

void action(string item) {
    System.Diagnostics.Debug.Write(item);
}

List<string> _listOfString = new List<string>();
Action<string> _action = new Action<string>(action);

// Code to add the values

_listOfString.ForEach(_action);

This chunk of code will output all values of your List into the Debug Window in Visual Studio.

As you can see, the .Net Framework 2.0 is very rich and provides means to automate your programming. Note that this methods that I have showed you will not make your program run faster. The execution time of doing it manually and by using delegates are similar. This is just a shorthand of tasks that you quite do repetitively.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:  
Actions:   E-mail | Permalink | Comments (6) | Comment RSSRSS comment feed

Comments

July 27. 2007 18:07

I've been using predicates for quite some time now and I find it more OOP friendly compared to the usual loop constructs we are used to. I'm glad though that Predicates are more prevalent in VS 2008 due to the introduction of LINQ. It's a very useful class IMHO and a lot of developers don't even know about it.

BeLe

August 3. 2007 03:08

pedro penduko

There's no need to create Predicates explicitly. Instead of:
Predicate matchDelegate = new Predicate(Match);
int[] resultArr = Array.FindAll(_myIntArray, matchDelegate);

You could simply write it this way:
int[] resultArr = Array.FindAll(_myIntArray, Match);

Same goes for the rest. Saving you another line of code Smile

pedro penduko

August 3. 2007 10:08

pauldomag

Yep, you can actually do this without declaring a predicate. But using predicates can make your code more versatile.

With predicates you can dynamically change the delegate in which your FindAll() function executes by just changing the underlying delegate in your predicate.

For example, you will present two choices for your user, either to choose items in an array greater than 5 or less than 5. So instead of writting 2 Array.Findall() routines you can just declare 1 and you can just change the delegate that your predicate is pointing to.

pauldomag

August 4. 2007 01:08

pedro penduko

Yes, you do make a good point Paul. That's where explicitly declaring delegates, in this case the Predicate, really come in handy. If the intention is to dynamically change the predicate at runtime, yours is the better approach. I'm simply pointing out a slight alternative based from your example without the declaration (it's created implicitly anyway).

Cheers Smile

pedro penduko

August 6. 2007 11:08

pauldomag

Yup, my example could've been more proper if I did a dynamically changing on the delegates. I was kinda lazy when I did the sample. BTW, do you have a Blog? Maybe I can link it here. It would be very great if I can link your blog here. Smile

pauldomag

August 20. 2007 05:08

pedro penduko

Hi Paul. I'm more of a lurker than a active poster but there are times when I just can't help it Laughing

Anyway, keep up the good work! Laughing

pedro penduko

Add comment


(Will show your Gravatar icon)  

biuquote
  • Comment
  • Preview
Loading