.Net C# 3.0 – Lambda Expressions

1 Comment

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: , , , ,

One Response to “C# 3.0 – Lambda Expressions”

  1. property in spain Says:

    I am normally ideas recognize the value of. This article really peaks my interest. on a regular basis

Leave a Reply