在foreach中从LINQ中选择2个值

时间:2013-05-13 13:24:33

标签: .net vb.net linq

我必须在同一个查询中选择另一列,因为在创建单行时我必须在同一行中添加该值。

//代码

  'Loop through the transactions
            For Each iTransactionid In (From TransactionFieldLinq In transactionFieldsCollection Select TransactionFieldLinq.TransactionId).Distinct

                'Create a new data row
                DataRow = DataTable.NewRow()

                'Set the data row properties
                DataRow("TransactionId") = iTransactionid

                'Loop through the transaction fields collection
                For Each TransactionField In (From TransactionFieldLinq In transactionFieldsCollection Where TransactionFieldLinq.TransactionId = CInt(DataRow("TransactionId")))

                    'Set the data row properties
                    DataRow(CStr(TransactionField.FieldId)) = TransactionField.FieldValue

                Next

                'Add the data row to the data table
                DataTable.Rows.Add(DataRow)

            Next

transactionFieldCollection有另一个名为StartDate的属性,格式为DateTime,我必须在同一个查询中选择StartDate列并将其绑定到{ {1}}喜欢TransactionId。

我如何实现这一目标?

3 个答案:

答案 0 :(得分:0)

您需要一个匿名类型。

(From TransactionFieldLinq In transactionFieldsCollection 
 Select TransactionFieldLinq.TransactionId, 
 TransactionFieldLinq.StartDate).Distinct

答案 1 :(得分:0)

select new {TransactionFieldLinq.TransactionId, 
 TransactionFieldLinq.StartDate}

答案 2 :(得分:0)

希望这有帮助。

//代码

'Loop through the transactions
                For Each iTransactionid In (From TransactionFieldLinq In transactionFieldsCollection Select TransactionFieldLinq.TransactionId).Distinct

                    'Create a new data row
                    DataRow = DataTable.NewRow()

                    'Set the data row properties
                    DataRow("TransactionId") = iTransactionid

                    'Loop through the transactions for start date
                    For Each dtStartDate In (From TransactionFieldLinq In transactionFieldsCollection Where TransactionFieldLinq.TransactionId = iTransactionid And TransactionFieldLinq.StartDate <> CDate("12:00:00 AM") Select TransactionFieldLinq.StartDate)

                        'Set the data row properties
                        DataRow("StartDate") = dtStartDate

                    Next
                    'Loop through the transaction fields collection
                    For Each TransactionField In (From TransactionFieldLinq In transactionFieldsCollection Where TransactionFieldLinq.TransactionId = CInt(DataRow("TransactionId")))

                        'Set the data row properties
                        If (TransactionField.FieldId <> 0) Then
                            DataRow(CStr(TransactionField.FieldId)) = TransactionField.FieldValue
                        End If
                    Next

                    'Add the data row to the data table
                    DataTable.Rows.Add(DataRow)

                Next