Tuesday, July 17, 2007

Predicates in .NET 2.0

I am not sure how many developers have used Predicates in .NET 2.0. Its a new generic type. When I first heard of it I tried finding it in some of the books and hardly any of the books mentioned about it and mostly it's been ignored. So I wrote some code to figure it out.
The task is I have a list of integers. I want to find all the numbers greater than 5 and copy it into another list without writing any looping code.
// declaring the predicate.
Predicate isGreater = new Predicate(pr.checkGreaterThanFive);
// passing the delegate to the findall method of the list
lst = anotherList.FindAll(isGreater);
that's it and your list is populated.
well, you need this method
public bool checkGreaterThanFive(int value)
{
if (value > 5)
return true;
else
return false;
}
Writing this method is boring so you can avoid it by creating anonymous method which makes your code smaller since you dont have to declare the Predicate nor write the method to call. Everything done in only one line of code.
lst = anotherList.FindAll(delegate(int value) { return value > 5; });

Here is the complete code
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
namespace PredConsole
{
class Program
{
static void Main(string[] args)
{
Program pr = new Program();
// Two empty list
List lst = new List();
List anotherList = new List();
anotherList.Add(1);
anotherList.Add(2);
anotherList.Add(3);
anotherList.Add(4);
anotherList.Add(5);
anotherList.Add(6);
anotherList.Add(7);
anotherList.Add(8);
anotherList.Add(9);
anotherList.Add(10);
anotherList.Add(11);
Predicate isGreater = new Predicate(pr.checkGreaterThanFive);
// With the created predicate
lst = anotherList.FindAll(isGreater);
pr.printResponse(lst);
lst = null;
// Using Anonymous methods is easier to write as well as understand.
lst = anotherList.FindAll(delegate(int value) { return value > 5; });
pr.printResponse(lst);
}
public bool checkGreaterThanFive(int value)
{
if (value > 5)
return true;
else
return false;
}
public void printResponse(List lst)
{
foreach (int iCount in lst)
{
Console.WriteLine(iCount);
}
Console.ReadLine();
}
}
}

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home