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 KaratasIEnumerable<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
|