2012-08-22 146 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