.Net → C# 3.0 – Lambda Expressions
So I answered a post on the Dream.In.Code forums about removing elements from a List that don’t meet a certain criteria, and I have decided to post that answer here.
Microsoft’s definition is, “A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.”
Here is a fairly simple example of using a lambda expression.
Student class
public class Student
{
public string Name;
public double Grade;
public Student(string _name, double _grade)
{
Name = _name;
Grade = _grade;
}
}
So our Student class has two properties for a student’s name and grade.
Main Program
List<Student> list = new List<Student>();
list.Add(new Student("You", 12));
list.Add(new Student("Me", 76));
list.Add(new Student("Them", 95));
// remove all students where Grade is less than 70
list.RemoveAll(li => li.Grade < 70);
foreach (Student s in list)
{
Console.WriteLine(s.Name + " " + s.Grade);
}
Console.Read();
So in our main program, we add 3 students to a list, then use a lambda expression to remove students who have a grade less than 70.
Tags: 3.0, 3.5, C#, expression, lambda
November 29th, 2011 at 5:20 AM
I am normally ideas recognize the value of. This article really peaks my interest. on a regular basis