Example explaining Func<T>

by sunil ravulapalli /28. September 2013 05:41 /c# /Comments (0)

Below is a simple program which shows three different ways we can pass the parameter to SingleOrDefault on a List<T>.

If essentially shows what Func<T> really is. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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" });

            //1
            var result1 = customers.SingleOrDefault(findFunction);
            Console.WriteLine(result1.Name);

            //2
            var result2 = customers.SingleOrDefault(delegate(Customer c)
                {
                    if (c.Id == 2)
                        return true;

                    return false;
                });
            Console.WriteLine(result2.Name);

            //3
            var result3 = customers.SingleOrDefault(c => c.Id == 3);
            Console.WriteLine(result3.Name);

            Console.ReadLine();
        }

        private static bool findFunction(Customer customer)
        {
            if (customer.Id == 1)
                return true;

            return false;
        }

    }

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