开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜