如何在不将其赋值给变量的情况下执行LINQ语句?

时间:2011-04-15 17:48:08

标签: vb.net linq lambda datatable

我有以下功能

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

我想知道是否有办法减少将LINQ结果分配给tmp并直接使用结果,即

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

2 个答案:

答案 0 :(得分:1)

你可以简单地在foreach循环中迭代它。 LINQ运算符的返回值为IEnumerable<T>内向,因此可迭代。

此外,您可以创建一个ForEach方法(由于LINQ堆栈的有副作用,因此不包含此方法,而ForEach是关于副作用的)作为IEnumerable<T>的附加信息,您无需先致电ToList

答案 1 :(得分:1)

是的,你可以,但你不能使用查询语法:

PositionsAdapter.GetData().Where(Function(pos) pos.SchoolID = SchoolID) _
                          .ToList().ForEach(Sub(i) positions.ImportRow(i))