Func Delegate
Func Delegate
==================================
Its a generic delegate.Is is symbolised by Func<T,TResult> . depending on the type paramemters (T and TResult) can be replaced with the corresponding type arguments
Func<Employee,string> specifies that it accepts Employee object and returns string object. Both Func<T,TResult> and lambda expression are similar things and differs only in sysntax.
Below is a code snippet with Func<T,TResult>
---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Indexers2
{
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
}
public partial class _Default : Page
{
List<Employee> employeelst;
protected void Page_Load(object sender, EventArgs e)
{
employeelst = new List<Employee>();
employeelst.Add(new Employee() { EmployeeId = 1, EmployeeName = "XXXX" });
employeelst.Add(new Employee() { EmployeeId = 2, EmployeeName = "YYYY" });
employeelst.Add(new Employee() { EmployeeId = 3, EmployeeName = "ZZZZ" });
Func<Employee, string> selector = employee => "Name=" + employee.EmployeeName;
IEnumerable<string> str= employeelst.Select(selector);
foreach (string str_ in str)
{
Response.Write(str_);
Response.Write("<br/>");
}
}
}
}
Below is a code snippet with Lambda expression
-------------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Indexers2
{
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
}
public partial class _Default : Page
{
List<Employee> employeelst;
protected void Page_Load(object sender, EventArgs e)
{
employeelst = new List<Employee>();
employeelst.Add(new Employee() { EmployeeId = 1, EmployeeName = "XXXX" });
employeelst.Add(new Employee() { EmployeeId = 2, EmployeeName = "YYYY" });
employeelst.Add(new Employee() { EmployeeId = 3, EmployeeName = "ZZZZ" });
//Func<Employee, string> selector = employee => "Name=" + employee.EmployeeName;
IEnumerable<string> str= employeelst.Select(n=> "Name ="+n.EmployeeName);
foreach (string str_ in str)
{
Response.Write(str_);
Response.Write("<br/>");
}
}
}
}
Comments
Post a Comment