How to execute a LINQ statement without assigning it to a variable?
I have the following function
Public Function GetPositionBySchoolID(ByVal SchoolID As Integer) As CPAPositionsDataTable
Dim positions As New CPAPositionsDataTable
Dim tmp = (From pos In PositionsAdapter.GetData()
Where (pos.SchoolID = SchoolID)
Select pos)
tmp.ToList.ForEach(Sub(i) positions.ImportRow(i))
Return positions
End Function
And I was wondering if there is a开发者_运维百科ny way to cut out assigning the LINQ result to tmp and just work with the result directly, i.e.
Public Function GetPositionBySchoolID(ByVal SchoolID As Integer) As CPAPositionsDataTable
Dim positions As New CPAPositionsDataTable
(From pos In PositionsAdapter.GetData()
Where (pos.SchoolID = SchoolID)
Select pos).ToList.ForEach(Sub(i) positions.ImportRow(i))
Return positions
End Function
Yes you can, but you can't use the query syntax:
PositionsAdapter.GetData().Where(Function(pos) pos.SchoolID = SchoolID) _
.ToList().ForEach(Sub(i) positions.ImportRow(i))
you can simply iterate over it in a foreach loop. The return value of the LINQ operators are IEnumerable<T>
deep down, so iterateable.
Also, you could create a ForEach
method (this wasn't included as the LINQ stack is about not having side effects, and ForEach
is all about side effects) as an extension on IEnumerable<T>
, you don't have to call ToList
before.
精彩评论