Example showing how you can use Func<T> in your own functions

by sunil ravulapalli /28. September 2013 06:09 /c# /Comments (0)

In the following example you can see that the Find function can re-used multiple times if we use Func<T>

namespace FuncTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var customers = new List<Customer>();

            customers.Add(new Customer { Id = 1, Name = "aaa"});
            customers.Add(new Customer { Id = 2, Name = "bbb" });
            customers.Add(new Customer { Id = 3, Name = "ccc" });

            var result1 = Find(customers, c => c.Id == 1);
            Console.WriteLine(result1.Id + " : " + result1.Name);

            var result2 = Find(customers, c => c.Name == "ccc");
            Console.WriteLine(result2.Id + " : " + result2.Name);

            Console.ReadLine();
        }

        private static Customer Find(List<Customer> customers, Func<Customer, bool> predicate)
        {
            return customers.SingleOrDefault(predicate);
        }
    }

    internal class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
blog comments powered by Disqus