本人初学LINQ,关于C#迭代器的概念也比较模糊。代码如下
DataClasses1DataContext db = new DataClasses1DataContext();
var q =
from c in db.Customers
select new
{
c.CustomerID,
CompanyInfo = new { c.CompanyName, c.City, c.Country },
ContactInfo = new { c.ContactName, c.ContactTitle }
};
foreach (var d in q)
{
//Response.Write(d.CompanyInfo);
foreach (IEnumerable<string> str in d.CompanyInfo)
{
Response.Write(str);
}
}
我是想遍历CompanyInfo 里的信息。但是这样写后总是提示:
错误 1 “AnonymousType#1”不包含“GetEnumerator”的公共定义,因此 foreach 语句不能作用于“AnonymousType#1”类型的变量
请问应该如何解决?还请高手指点
错误已经提示的很明确了,楼主何必再发贴问呢?
因为你的CompanyInfo 不是一个集合
mark...
DataClasses1DataContext db = new DataClasses1DataContext(); var q = (from c in db.Customers select new { c.CustomerID, CompanyInfo = new { c.CompanyName, c.City, c.Country }, ContactInfo = new { c.ContactName, c.ContactTitle } }).ToList(); foreach (var d in q) { //Response.Write(d.CompanyInfo); foreach (IEnumerable<string> str in d.CompanyInfo) { Response.Write(str); } }
这样试试