var query =
from c in Customers
where c.Country == "USA"
select new { c.CompanyName,c.Country};
//查看query的类型
System.Data.Linq.DataQuery`1[[<>f__AnonymousType0`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
里面包含了 System.Data.Linq.DataQuery`1[String,String]
foreach (var company in query)
{
Console.WriteLine(company.GetType());
Console.WriteLine(company);
}
而company的类型如下,可以简化看成[String,String]
<>f__AnonymousType0`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
并且如上的foreach代码则在实际执行中,等价于如下代码:
//IEnumerator<string> enumerator = query.GetEnumerator();
var enumerator = query.GetEnumerator(); //用var代替IEnumerator<string>,因为上面查询的是new形式select new { c.CompanyName,c.Country};
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}