terça-feira, 14 de julho de 2009

Predicate Delegate

Um predicate é uma função que retorna true ou false. O predicate delegate é uma referencia para o predicate.

Então basicamente um predicate delegate é uma referencia para uma função que retorna true ou false. Predicates são normalmente aplicáveis para filtar lista de valores. Veja um exemplo:

using System;
using System.Collections.Generic;

class Program
{
   
static void Main()
   
{
       
List<int> list = new List<int> { 1, 2, 3 };

       
Predicate<int> predicate = new Predicate<int>(pegueMaiorQueDois);

       
List<int> novaList = list.FindAll(predicate);
   
}

   
static bool pegueMaiorQueDois(int arg)
   
{
       
return arg > 2;
   
}
}

Agora se você utiliza o C# 3 você pode usar uma expressão lambda para representar o predicate:

using System;
using System.Collections.Generic;

class Program
{
   
static void Main()
   
{
       
List<int> list = new List<int> { 1, 2, 3 };

       
List<int> novaList = list.FindAll(i => i > 2);
   
}
}
Você também pode de um jeito direto, colocar a função:
 
using System;
using System.Collections.Generic;

class Program
{
   
static void Main()
   
{
       
List<int> list = new List<int> { 1, 2, 3 };

       
List<int> newList = list.FindAll(delegate(int arg)
                           
{
                               
return arg> 2;
                           
});
   
}
}