查询理解语法-这允许你写在一个 SQL 样的结构。所有这些东西都被转换成 System 上的方法。Linq.可查询或系统。Linq.枚举数(取决于 myCustomer 的类型)。它是完全可选的,您可以在没有它的情况下很好地使用 LINQ。这种查询声明样式的一个优点是范围变量的作用域: 它们不需要为每个子句重新声明。
IEnumerable<string> result =
from c in myCustomers
where c.Name.StartsWith("B")
select c.Name;
Lambda Expressions - This is a shorthand for specifying a method. The C# compiler will translate each into either an anonymous method or a true System.Linq.Expressions.Expression. You really need to understand these to use Linq well. There are three parts: a parameter list, an arrow, and a method body.
IEnumerable<string> result = myCustomers
.Where(c => c.Name.StartsWith("B"))
.Select(c => c.Name);`
Anonymous Types - Sometimes the compiler has enough information to create a type for you. These types aren't truly anonymous: the compiler names them when it makes them. But those names are made at compile time, which is too late for a developer to use that name at design time.
myCustomers.Select(c => new
{
Name = c.Name;
Age = c.Age;
})
Implicit Types - Sometimes the compiler has enough information from an initialization that it can figure out the type for you. You can instruct the compiler to do so by using the var keyword. Implicit typing is required to declare variables for Anonymous Types, since programmers may not use the name of an anonymous type.
// The compiler will determine that names is an IEnumerable<string>
var names = myCustomers.Select(c => c.Name);