2012-08-22 82 views
0

我有一个LINQ查询,如下所示:循环通过Linq查询

Dim CustQuery = From a In db.Customers 
       Where a.GroupId = sendmessage.GroupId 
       Select a.CustCellphone 

,并想经过每个结果,并得到了手机号码做的代码peice的。我尝试了以下,但似乎无法得到它正确的:

For Each CustQuery.ToString() 
    ... 
Next 

所以我的问题是如何做到这一点?

回答

5

您必须在For Each循环中设置一个变量,以存储集合中每个项目的值,供您在循环中使用。对于VB For Each循环正确的语法是:

For Each phoneNumber In CustQuery 
    //each pass through the loop, phoneNumber will contain the next item in the CustQuery 
    Response.Write(phoneNumber)  
Next 

现在,如果你的LINQ查询是一个复杂的对象,你可以使用循环下列方式:

Dim CustQuery = From a In db.Customers 
       Where a.GroupId = sendmessage.GroupId 
       Select a 

For Each customer In CustQuery 
    //each pass through the loop, customer will contain the next item in the CustQuery 
    Response.Write(customer.phoneNumber)  
Next