Métodos Anónimos y Predicados en C# – Parte II

¿Y qué es un predicado?

Si utilizaron listas genéricas se habrán encontrado con que algunos método, como Find por ejemplo, toman como parámetro un predicado, bien, esto no es más que un delegado pero con una firma diferente, vamos a ver la definición:

       public delegate bool Predicate<T>(T obj);

Está claro que es un delegado que define un método que acepte un tipo T (cualquiera) y que retorne bool. Esto es para indicar que el objeto que pasa como parámetro cumple con el criterio de búsqueda, vamos a ver el método Find de la lista genérica. Echamos mano del Reflector para variar y vemos esto:

   1:  public T Find(Predicate match)

   2:  {

   3:      if (match == null)

   4:      {

   5:        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);

   6:      }

   7:      for (int i = 0; i < this._size; i++)

   8:      {

   9:          if (match(this._items[i]))

  10:          {

  11:              return this._items[i];

  12:          }

  13:      }

  14:      return default(T);

  15:  }


Vemos que el truco está en la línea 9, ahí llama al predicado y le pregunta si el item actual (dentro de la iteración) cumple con alguna condición que estará en el predicado.
Vamos a ver una aplicación práctica

 

Ejemplo :

    class EndsWith

    {

        private string m_Suffix;

 

        // Initializes with suffix we want to match.

        public EndsWith(string Suffix)

        {

            m_Suffix = Suffix;

        }

 

        // Sets a different suffix to match.

        public string Suffix

        {

            get { return m_Suffix; }

            set { m_Suffix = value; }

        }

 

        // Gets the predicate.  Now it’s possible to re-use this predicate with various suffixes.

        public Predicate<string> Match

        {

            get { return IsMatch; }

        }

 

        private bool IsMatch(string s)

        {

            if ((s.Length >= m_Suffix.Length) &&

                (s.Substring(s.Length – m_Suffix.Length).ToLower()

                                                     == m_Suffix.ToLower()))

            {

                return true;

            }

            else

            {

                return false;

            }

        }

    }

 

    public class DinoClassification

    {

        public void Classify()

        {

            List<string> dinosaurs = new List<string>(new string[] {

            "Compsognathus", "Amargasaurus", "Oviraptor", "Velociraptor",

            "Deinonychus", "Dilophosaurus", "Gallimimus", "Triceratops"});

 

            Console.WriteLine("\nFind(EndsWith): {0}",

                dinosaurs.Find(new EndsWith("saurus").Match));

 

            EndsWith predicate = new EndsWith("tor");

 

            Console.WriteLine("\nFind(EndsWith): {0}",

                dinosaurs.Find(predicate.Match));

 

            predicate.Suffix = "hus";

 

            Console.WriteLine("\nFind(EndsWith): {0}",

                dinosaurs.Find(predicate.Match));

        }

    }

 

    public class Example

    {

        public static void Main()

        {

            DinoClassification dcl = new DinoClassification();

            dcl.Classify();

        }

    }

 lo corremos y vemos que funciona.

 

Ejemplo Predicados

 

Aquí esta URL para leer algo más sobre el tema:

http://www.mediacenter.vb-mundo.com/index.php?option=com_content&task=view&id=37

 

Published by justindeveloper

I am MCP (Microsoft Certified Professional). MCTS (Microsoft Certified Technology Specialist) and MCPD (Microsoft Certified Professional Developer), also I am SAP Business One Certified!! Desarrollando desde el IDE de Visual Studio NET 2003 hasta ahora con el Visual Studio NET 2010. Desde Microsoft SQL Server 2000 hasta ahora con el Microsoft SQL Server 2008 R2 y tambien con SharePoint, desde WSS 3.0 y MOSS 2007 y ahora familirizandome con el Sharepoint Foundation 2010 & Sharepoint Server 2010. The software development will follow being every time more wonderful!

Leave a comment