Home >

Sample Code of Func<T,bool>

6. October 2009
Just some sample code of passing a predicate into a method.
 
using System; 

namespace Func 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            string[] weekDays = {"Sun", 
                                 "Sat", 
                                 "Mon", 
                                 "Tue", 
                                 "Wed", 
                                 "Thu", 
                                 "Fri"}; 

            Display(weekDays, s => s.StartsWith("S") );
            Console.WriteLine();
            Display2(weekDays, s => s.Length > 2);
            Console.ReadLine();
        }

        private static void Display<T>(T[] name, Func<T, bool> func)
        {
            foreach (T s in name)
            {
                if(func(s))Console.WriteLine(s);
            }
        }

        private static void Display2(string[] name, Func<string, bool> func)
        {
            foreach (string s in name)
            {
                if (func(s)) Console.WriteLine(s);
            }
        }

    }
}
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5