我正在使用DataTable Column,我想将一列数据表提取到String数组,然后想要分配给 AutoCompleteStringCollection 对象。目前我正在填充' AutoCompleteStringCollection'使用循环,但如果我有超过500行,则需要时间。我想用循环来做这个。任何人都可以建议更好的方式。
Dim autocomp As New AutoCompleteStringCollection
For index As Integer = 0 To unionTable.Rows.Count - 1
autocomp.Add(unionTable.Rows(index)(1).ToString())
Next
我想没有循环,请帮助
经过一番努力,我设法做到了。使用.Net 3.5框架Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim table1 As DataTable = New DataTable("Test")
table1.Columns.Add("name")
table1.Columns.Add("id")
table1.Rows.Add("Abb", 1)
table1.Rows.Add("Killers", 2)
Dim allAutoCompletes = From row In table1.AsEnumerable()
Let autoComplete = row.Field(Of String)(0)
Select autoComplete
Dim autoCompleteString As String() = allAutoCompletes.ToArray()
Dim x As String = ""
Dim autocomp As New AutoCompleteStringCollection
autocomp.AddRange(autoCompleteString)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
答案 0 :(得分:5)
你总是要使用一个循环。但你可以使用看起来更好的LINQ:
Dim allAutoCompletes = From row In unionTable.AsEnumerable()
Let autoComplete = row.Field(Of String)(1)
Select autoComplete
Dim autoCompleteStringCollection As String() = allAutoCompletes.ToArray()
如果您想List(Of String)
使用ToList
。
这里的方法语法与上面相同,使用你觉得更具可读性的内容:
Dim autoCompleteStringCollection As String() = unionTable.AsEnumerable().
Select(Function(r) r.Field(Of String)(1)).
ToArray()
答案 1 :(得分:0)
Rango的代码对我来说非常有用。这是作为扩展的代码,可以将其放在任何公共模块中,并通过在要为其启用以下功能的类中添加“导入扩展”来使用:
df['New Group'] = np.where(df['Old Group'].str.contains("Stark"), 'Stark Family', 'Other')
使用:
Public Module Extensions
''' <summary>Build string array from specified column in DataTable.</summary>
''' <returns>String()</returns>
<Extension()>
Public Function ColumnToStringArray(ByVal dataTable As DataTable, columnIndex As Integer) As String()
Dim allAutoCompletes = From row In dataTable.AsEnumerable()
Let autoComplete = row.Field(Of String)(columnIndex)
Select autoComplete
Return allAutoCompletes.ToArray()
End Function
End Module