Adding rows and columns from a datatable to dictionary

i’m adding rows of a datable to a dictionary, proceed to do something, clear the dictionary then repeat.
is there any linq or a one line code instead of using for each row, then for each column to add the key-value pair?

column name is the key, whereas row value is the value

@TyraS

Try this

Dt.AsEnumerable.ToDictionary(function(x) x("ColumnName1").ToString,function(x) x("ColumnName2").ToString)

I hope you mean you have 2 columns and many rows

Cheers

Hi @TyraS

Please give this expression a try:

Dim dataTable As New DataTable()

Dim dictionary = dataTable.Rows.Cast(Of DataRow)() _
    .ToDictionary(Function(row) row("ColumnName").ToString(), Function(row) row("ColumnName").ToString())

dictionary.Clear()

Hope this helps,
Best Regards.

hi, i meant many rows and many columns
for each row, i’ll add to dictionary the row values and the column keys as key?

Hi @TyraS ,

Can you share screenshot of the workflow which you have done with For Each activity?
It might help us to provide you the solution.

hi,
datatable:
image

for each row:

How about this:
row.Table.Columns.Cast(Of DataColumn)().ToDictionary(Function(c) c.ColumnName, Function(c) row(c))

Edit: To be used inside For Each Row.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.