class ShowAllUsers
{
static void Main()
{
var query = from user in SampleData.AllUsers
select user;
//query
//System.Linq.Enumerable.WhereSelectListIterator
foreach (var user in query)
//foreach 后 query 后 in 调用 select 后 var user
// var user多次赋值 null
//{User: Tim Trotter (Tester)}
//{User: Tara Tutu (Tester)}
//{User: Deborah Denton (Developer)}
//{User: Darren Dahlia (Developer)}
//{User: Mary Malcop (Manager)}
//{User: Colin Carton (Customer)}
{
Console.WriteLine(user);//WriteLine会调用重载的ToString方法
//为每个实体重写了ToString方法
}
}
}
public class User
{
public string Name { get; set; }
public UserType UserType { get; set; }
public User (string name, UserType userType)
{
Name = name;
UserType = userType;
}
public override string ToString()
{
return string.Format("User: {0} ({1})", Name, UserType);
}
}
public static class Users
{
public static readonly User TesterTim = new User("Tim Trotter", UserType.Tester);
public static readonly User TesterTara = new User("Tara Tutu", UserType.Tester);
public static readonly User DeveloperDeborah = new User("Deborah Denton", UserType.Developer);
public static readonly User DeveloperDarren = new User("Darren Dahlia", UserType.Developer);
public static readonly User ManagerMary = new User("Mary Malcop", UserType.Manager);
public static readonly User CustomerColin = new User("Colin Carton", UserType.Customer);
}
public enum UserType : byte
{
Customer,
Developer,
Tester,
Manager,
}
以数据源作为开始,以选择作为结束
在C#3中每个查询表达式都以同样的方式开始--声明一个数据序列的数据源:
from element in source
element只是一个标识符,前面可以放置一个类型名称。 大多数情况下,你
都不需要类型名称。source是一个普通的表达式。在第一个子句出现之后,
许多不同的事情会发生,不过迟早都会以一个select子句或group子句来结束。
select expression
select子句被称为投影。
把两者结合在一起,然后用这个微不足道的表达式来作为我们的简单查询。
我们用这个查询表达式介绍两个概念,使用转换过程,范围变量
输出
User: Tim Trotter (Tester)
User: Tara Tutu (Tester)
User: Deborah Denton (Developer)
User: Darren Dahlia (Developer)
User: Mary Malcop (Manager)
User: Colin Carton (Customer)