Karatas, FERHAT
I would love to change the world, but they won't give me the source code!
Lambda Expression
23.05.2009 13:39:41 - Filed under : C# | LINQ
Lambda Expressions provide a more concise,  functional syntax for writing anonymous methods.  They end up being  super useful when writing LINQ query expressions - since they provide a  very compact and type-safe way to write functions that can be passed as  arguments for subsequent evaluation. 
 
Example:
 
Sample 1 : 
public class Person
{
  public string FirstName;
  public string LastName;
  public int Age;
}

List<person> people = new List<person>
{
    new Person{FirstName = "Ferhat", LastName = "Karatas", Age=10},
    new Person{FirstName = "Elif", LastName = "Sila", Age=5},
    new Person{FirstName = "Sevim", LastName = "Karatas", Age=15}
}; 
 
// return all Karatas
IEnumerable<person> results = people.Where(p => p.LastName == "Karatas");
double averageAge = people.Average(p => p.Age);
Label1.Text = results.Count().ToString() + "-" + averageAge.ToString();

Sample 2 :

var numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var evennumber = numbers.FindAll(p => p % 2 == 0);
foreach (int item in evennumber)
{
    Label1.Text += item + "-";

 
The p => expressions highlighted above  in red are Lambda expressions.  In the sample above I'm using the first  lambda to specify the filter to use when retrieving people, and the  second lambda to specify the value from the Person object to use when  computing the average.

Keywords : Linq, lambda expression
with 0 comments

What do you think ?
Security Code 5316
Check S. Code
Name  
Email  
Home Page  
Comments