如何在LINQ查询中增加counter
?
考虑以下
Public Class SimpleString
Public Property Value As String
End Class
...
Public Shared Sub SetStuff()
Dim stringList As IEnumerable(Of SimpleString) =
{New SimpleString With {.Value = "0"},
New SimpleString With {.Value = "0"},
New SimpleString With {.Value = "0"},
New SimpleString With {.Value = "0"},
New SimpleString With {.Value = "0"}}
Dim counter As Integer = 0
Dim newIntegerList As IEnumerable(Of SimpleString) =
(From i In stringList
Select New SimpleString With
{
.Value = (counter = counter + 1).ToString
})
End Sub
以上不起作用。
规则:
答案 0 :(得分:1)
因为VB.NET中的赋值和equals运算符完全相同,所以你不能做VB.NET相当于:
Value = (counter = counter + 1).ToString()
增加变量并将其打印为字符串。
但是,您可以编写一个带有Integer
ByRef
的辅助方法,将其递增并返回:
Public Function Increment(ByRef value As Integer) As Integer
value = value + 1
Return value
End Function
在查询中使用它:
Dim newIntegerList As IEnumerable(Of SimpleString) =
(From i In stringList
Select New SimpleString With
{
.Value = Increment(counter).ToString
})
但我不得不说,我真的根本不理解你的规则 ......
答案 1 :(得分:0)
只是为了好玩,除了Marcin's correct answer之外,您还可以使用枚举器并使用Let
- 子句产生副作用:
Dim gen = Enumerable.Range(1, Int32.MaxValue).GetEnumerator()
Dim newIntegerList As IEnumerable(Of SimpleString) = _
(From i In stringList
Let tmp = gen.MoveNext()
Select New SimpleString With
{
.Value = gen.Current()
})
另外,只是为了记录,使用方法语法(在这种情况下我更喜欢):
Dim newIntegerList As IEnumerable(Of SimpleString) = _
stringList.Select(Function(v, i) New SimpleString With
{
.Value = i + 1
})