I am using LINQpad to get a grasp of LINQ and in one of the XML examples they have the following code
var bench =
new XElement ("bench",
new XElement ("toolbox",
new XElement ("handtool", "Hammer"),
new XElement ("handtool", "Rasp")
),
new XElement ("toolbox",
new XElement ("handtool", "Saw"),
new XElement ("powertool", "Nailgun")
),
new XComment ("Be careful with the nailgun")
);
var toolboxWithNailgun =
from toolbox in bench开发者_开发百科.Elements()
where toolbox.Elements().Any (tool => tool.Value == "Nailgun")
select toolbox.Value;
I am curious about tool => tool.Value == "Nailgun"
What exactly is going on there?
That's a C# Lambda Expression which are used to quickly specify anonymous functions. This particular lambda function returns true if the tool.Value is "Nailgun"
Lambda expression, IOW a function defined inline.
The compiler actually turns the Lambda into a class which has fields that reference everything the lambda does. If you open an assembly that contains lambda expressions, you'll see these classes with weird names such as <string>b_0() : Void
.
Lambdas also rely on lots of type inference by the compiler. While you can be explicit about the types involved within the lambda, you can usually let the compiler figure it out on its own. Have no doubt that the compiler ensures the lambda is strongly typed, even though you don't specify them.
This function:
public string Foo(int bar)
{
return bar.ToString();
}
can be expressed as lambdas in the following ways:
x => x.ToString()
bar => bar.ToString()
int bar => bar.ToString()
(int bar) =>
{
return bar.ToString();
}
They are all equivalent.
It's called a lambda and isn't a LINQ feature per-se.
It means it will match any elements where the tool value is equal to "Nailgun".
That would be a classic example of the Lambda Operator (in action inside of a Lambda Expression).
=>
is the lambda operator in C#. In this case, you're calling the Linq Any() function which takes a predicate, a function which takes some parameter(s) and returns a boolean. A predicate is often used to determine whether to select an item or not. Linq calls this lambda predicate for every tool in the collection.
On the left of the =>
is the lambda argument, in this case the tool to be tested and on the right is a boolean expression which returns true only when the tool's Value is "Nailgun". Therefore, the Any() function returns true only if one of the tools is a nail gun.
That means any tool whose Value property (which is the character data in each element) is equal to "Nailgun". As Any() walks the tools in the toolbox, the lambda expression is executed and its result (a bool) is returned back from the lambda expression.
精彩评论