I know what this code is doing but I’m not sure on the syntax. It doesn’t seem to conform to a “standard” format. Is it mostly LINQ?
return db.Subjects.SingleOrDefault(s => s.ID == ID);
The first part makes sense but it’s the part in the brackets I don’t understand. How can we use s without declaring it? And how are we putting logic into a method call?
What are you seeing here is a lambda expression. It’s a very special anonymous delegate.
Enumerable.SingleOrDefaultis a LINQ method, but the lambdas are something independent of LINQ; they just make LINQ incredibly more friendly then it otherwise would be.Now, to get specific
IEnumerable<Subject>.SingleOrDefault(s => s.ID == ID)returns the unique instance ofSubjectin theIEnumerable<Subject>that matches the predicates => s.ID == IDor it returnsnullif there is no such instance. It throws an exception if there is more than one such instance. At compile-times => s.ID == IDis translated into a full-blown delegate the eats objects of typeSubjectand returns aboolthat istrueif and only ifs.IDis equal toID.The
=>is the lambda operator. It basically separates the left-hand side of the lambda expression from the right-hand side. The left-hand side are the input variables. It’s equivalent to the parameter list in an explicitly-defined method. That issin the lambda expression plays the role ofsbelow:It’s just that you don’t have to declare the type of
sas the compiler will infer it.The right-hand side the lambda body. It’s equivalent to the body below
What is more, you don’t have to declare the return type; the compiler will infer that to.
So, in the end it is as if you did the following:
Then:
The nice thing is the compiler just automatically spits this out for you when you use a lambda expression.