普通寫法
#Python編寫:
a = []
for x in range(21):
if x%2==0:
a.append(x)
print(a)
'Visual Basic編寫:
Sub main()
Dim so As New ArrayList
For x = 0 To 20
If x Mod 2 = 0 Then
so.Add(x)
End If
Next
End Sub
運行結果:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
高級寫法
#Python List comprehension寫法:
a = [x for x in range(21) if x%2==0]
print(a)
'Visual Basic
??????
YES
用VB.net版的LAMBDA
Sub Main()
Dim alist(100) As Int32 '弄一個100維度的陣列
For i = 1 To 100
alist(i) = i ' 塞預設值
Next
For Each a In alist.Where(Function(x) x Mod 2 = 0) ' 只列出除以2餘0的數字(偶數)
Console.WriteLine(a)
Next
End Sub
NO, 用VB不行。
但用EXCEL VBA可以做出類似的效果。
Sub test()
Dim a As Variant, myRng As Range, i As Long
Set myRng = Range(Cells(1, 1), Cells(10, 1))
myRng.FormulaR1C1 = "=row()*2"
a = Application.Transpose(myRng)
For i = LBound(a) To UBound(a)
Debug.Print (a(i))
Next i
End Sub
Python不熟, 不過我猜你的需求是不是這樣
以下是C#的寫法,要轉成VB的應該也不難
Random rnd = new Random();
List<int> list = Enumerable.Range(1, 50).OrderBy(n => rnd.Next()).ToList();
list = list.Select(x => x * 2).ToList();
for (int i = 0; i < list.Count; i++)
Console.Write($"{list[i]} ");