对于vb.net中的每个循环

时间:2009-08-25 15:16:06

标签: .net vb.net foreach for-loop

如何在vb.net中使用for循环,如

dim start as integer
Dim customers as New List(Of Customers)

Customers=dataAcess.GetCustomers()

For each start=500 in  Customers.count
  'Do something here'
Next

我想为每500位客户处理一些数据..请帮忙

8 个答案:

答案 0 :(得分:7)

尝试以下

For Each current In customers
  '' // Do something here 
  Console.WriteLine(current.Name)
Next

答案 1 :(得分:7)

首先,如果您要在下一行为参考分配不同的列表,请不要创建New客户列表。那有点蠢。这样做:

Dim customers As List(Of Customer) = dataAccess.GetCustomers()

然后,对于循环,您需要一个简单的“For”循环而不是每个循环。不要忘记在列表结尾之前停止:

For i As Integer = 500 To Customers.Count -1 
    'do something with Customers(i) here
Next i

如果您使用的是Visual Studio 2008,您也可以这样写:

For each item As Customer in  Customers.Skip(500)
   'Do something with "item" here
Next

答案 2 :(得分:1)

'这将从500开始并处理到结束....

for start as integer = 500 to Customers.Count

'process customer....
customer = Customers(start)

Next

迭代整个列表:

for each cust as Customer in Customers

Next 

一个注意事项...... VB不区分大小写,您的示例代码似乎使用小写和大写客户

答案 3 :(得分:1)

这样的事情: -

Dim customers as New List(Of Customer)

Customers=dataAcess.GetCustomers()

For Each customer AS Customer in  Customers
   '' // do something with the customer object
Next

修改

听起来您想要选择N个项目中的500个或者接下来的500个项目。您可以使用LINQ扩展方法.Take和/或.Skip来实现此目的。然后使用ToList创建列表。 E.g: -

Dim customers as List(Of Customer)
customers = dataAccess.GetCustomers().Skip(500).Take(500).ToList()

如果您只想通过客户进行枚举,那么您可以省去ToList()。

答案 4 :(得分:0)

您可以尝试:

    For i As Integer = 500 To (customers.Count -1)
        ''do something
    Next

或者

    For i As Integer = 0 To (customers.Count - 1) step 500
        ''do something
    Next

答案 5 :(得分:0)

Dim start as Integer
Dim customers as New List(Of Customers)

Customers = dataAcess.GetCustomers()

For i as Integer = start to Customers.count Step 500
    Debug.Print Customers(i).someProperty
    Do something here
Next i

我认为你需要使用Customer索引和Steps in 500s。这只会处理客户(开始),客户(开始+ 500),客户(开始+ 1000)等,而不是所有客户。这是你想要的吗?

答案 6 :(得分:0)

我不确定你要做什么,但也许你可以试试这个:

Dim count As Integer = 0
Const MAX_CUSTOMERS As Integer = 500
Dim customers As List(Of Customers) = dataAcess.GetCustomers()

For Each c As Customer In customers
    'do stuff here'
    c.Name = "Billy"
    count+=1

    If count = MAX_CUSTOMERS Then Exit For
Next

它无论如何都不优雅,但它有意义,它会起作用。

答案 7 :(得分:0)

显然,品种并不缺乏。我不认识你的“DataAcess”对象类型,但如果你可以将该表作为Recordset(即一个SQL表)拉出来,那么试试这个。 (完成后不要忘记返回记录集)

Option Explicit

Dim Customers As Recordset
Set Customers=currentdb.openrecordset("???")

While Customers.EOF=False
   'do stuff here using the recordset object
   'i.e. Customers.Fields("Name")="Billy"
   Customers.MoveNext
Wend