This is a goes to
operator (or lambda operator), which used in lambda expressions (anonymous methods creation) to separate input variables from lambda body.
In your sample students.Find(i => i.Id== id)
input variable i
goes to lambda body i.Id == id
(i.e. passed as a anonymous method parameter).
Also take a look on on List<T>.Find
method, which you are using. It accepts predicate of type T
, which in your case will be Predicate<Student>
. Predicated is a delegate, which represents method that defines a set of criteria and determines whether the specified object meets those criteria. It has following signature:
public delegate bool Predicate<in Student>(Student obj)
So, you need to pass a method, which accepts a student object and returns a bool. You can create normal named method for this:
private bool IsStudentHasIdEqualTo5(Student s)
{
return s.Id == 5;
}
And use it this way:
Student aStudent = students.Find(IsStudentHasIdEqualTo5);
But you need to verify for different id values. There is two options - either create field in your class, which will be available inside student predicate method, or create class, which will have both this method and field:
class StudentSearcher
{
private int _id; // capture id
public StudentSearcher(int id)
{
_id = id;
}
// method has same signature as bool Predicate(Student obj)
public bool VerfyId(Student s)
{
return s.Id == _id;
}
}
Now you can use this named method and provide different id
values for student verification:
var searcher = new StudentSearcher(id);
Student aStudent = students.Find(searcher.VerfyId);
But creating such methods and classes for each search is not very efficient. This is why we have delegates (and lambdas). Instead of declaring new named method, you can create method without name (anonymous) exactly in place where you need it, and compiler will generate usual named method for you:
Student aStudent = students.Find(delegate(Student s) {
return s.Id == id;
});
Exactly same code could be written in lambda syntax (delegate keyword omitted, parameter type inferred, goes to
operator used to separate parameter and method body, return keyword also omitted):
Student aStudent = students.Find(s => s.Id == id);
The magic here is that compiler will generate class like one shown above behind the scene. That class will have method with predicate signature, and also it will have field for capturing id
to search for.