Need to change this code.Linq Set To DataTable

Mansour_Dalir 2,036 Reputation points
2023-06-07T18:10:34.07+00:00

hi

need Set to dataTable with 2 column

         Dim MyDataTable New DataTable
        MyDataTable.Columns.Add("Key")
        MyDataTable.Columns.Add("Values")
        MyDataTable.Rows.Add({"a", "1"})
        MyDataTable.Rows.Add({"b", "2"})
        MyDataTable.Rows.Add({"a", "3"})
        MyDataTable.Rows.Add({"c", "4"})
        MyDataTable.Rows.Add({"a", "5"})
        MyDataTable.Rows.Add({"c", "6"})

       Dim q = From row In MyDataTable.AsEnumerable()
                Group row("Valuse") By key = row("Key") Into Group
                Select New With {.Key = key, .Values = String.Join(",", Group.Select(Function(r) r.ToString()))}


 Dim distinctTable As DataTable = New DataTable()
   distinctTable.Columns.Add("KEY", GetType(String))  
   distinctTable.Columns.Add("Values", GetType(String))  
   Dim distinctRows = q.Select(Function(value) 
distinctTable.LoadDataRow(New Object() {value}, False))
Dim dt As DataTable = distinctRows.CopyToDataTable()

Output On DataTable with 2 Columns Key and Valuse

a 1,3,5

b 2

c 4,6

thank

Developer technologies | VB
{count} votes

Answer accepted by question author
  1. Jiachen Li-MSFT 34,231 Reputation points Microsoft External Staff
    2023-06-08T01:41:45.8266667+00:00

    Hi @Mansour_Dalir

    You need to pass the "Key" and "Values" values as separate parameters to the LoadDataRow method to ensure that they match the column structure of the DataTable.

    Dim q = From row In MyDataTable.AsEnumerable()
            Group row.Field(Of String)("Values") By key = row.Field(Of String)("Key") Into Group
            Select New With {.Key = key, .Values = String.Join(",", Group)}
    
    Dim distinctTable As DataTable = New DataTable()
    distinctTable.Columns.Add("Key", GetType(String))
    distinctTable.Columns.Add("Values", GetType(String))
    Dim distinctRows = q.Select(Function(item) distinctTable.LoadDataRow(New Object() {item.Key, item.Values}, False))
    Dim dt As DataTable = distinctRows.CopyToDataTable()
    
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.