How to group the DataTable together with an array. 'Linq'

Mansour_Dalir 2,036 Reputation points
2023-06-24T16:11:23.4866667+00:00

hi

And how to get to the index number ("b") On ( OutPut Array)

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

        'need this Result
        Dim OutPut = {({"a", ({1, 3, 4})}), ({"b", ({2})}), ({"c", ({5, 6})})}
Developer technologies | VB
0 comments No comments
{count} votes

Answer accepted by question author
  1. Jiachen Li-MSFT 34,231 Reputation points Microsoft External Staff
    2023-06-26T02:30:58.9233333+00:00

    Hi @Mansour_Dalir , You can refer to the following code, using GroupBy in linq.

            Dim outputArray = MyDataTable.AsEnumerable().
        GroupBy(Function(row) row.Field(Of String)("B")).
        Select(Function(group) New Tuple(Of String, List(Of Integer))(group.Key, group.Select(Function(row) Integer.Parse(row.Field(Of String)("A"))).ToList())).
        ToArray()
    

    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.

1 additional answer

Sort by: Most helpful
  1. Mansour_Dalir 2,036 Reputation points
    2023-06-26T06:44:25.0233333+00:00
            Dim ArrOut = From iRow In MyDataTable.AsEnumerable()
            Group iRow.Item("A") By Head = iRow.Item("B") Into Group
            Select New Object() {Group, Head}
            ArrOut = ArrOut.ToArray
    
    0 comments No comments

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.