LINQ 查询
对查询变量使用有意义的名称。下面的示例为位于西雅图的客户使用 seattleCustomers。
var seattleCustomers = from cust in customers
where cust.City == "Seattle"
select cust.Name;
使用别名确保匿名类型的属性名称都使用 Pascal 大小写格式正确大写。
var localDistributors =
from customer in customers
join distributor in distributors on customer.City equals distributor.City
select new { Customer = customer, Distributor = distributor };
如果结果中的属性名称模棱两可,请对属性重命名。例如,如果你的查询返回客户名称和分销商 ID,而不是在结果中将它们保留为 Name 和 ID,请对它们进行重命名以明确 Name 是客户的名称,ID 是分销商的 ID。
var localDistributors2 =
from cust in customers
join dist in distributors on cust.City equals dist.City
select new { CustomerName = cust.Name, DistributorID = dist.ID };
在查询变量和范围变量的声明中使用隐式类型化。
var seattleCustomers = from cust in customers
where cust.City == "Seattle"
select cust.Name;
对齐 from 子句下的查询子句,如上面的示例所示。
在其他查询子句之前使用 where 子句,以确保后面的查询子句作用于经过减少和筛选的数据集。
var seattleCustomers2 = from cust in customers
where cust.City == "Seattle"
orderby cust.Name
select cust;
使用多行 from 子句代替 join 子句以访问内部集合。例如,Student 对象的集合可能包含测验分数的集合。当执行以下查询时,它返回高于 90 的分数,并返回得到该分数的学生的姓氏。
// Use a compound from to access the inner sequence within each element.
var scoreQuery = from student in students
from score in student.Scores
where score > 90
select new { Last = student.LastName, score };
注:相关教程知识阅读请移步到c#教程频道。










