How to relationship two DataTable and get Results in the third DataTable using Linq commands? Without the use of for loop

Mansour_Dalir 1,716 Reputation points
2023-06-04T04:52:16.7233333+00:00

hi

I want without using the for loop .thank

I asked this question before, but this time I need the linq method. in:

https://learn.microsoft.com/en-us/answers/questions/1288478/how-to-relationship-two-datatable-and-get-results


        Dim dtParent As New DataTable
        Dim dtChild As New DataTable
        Dim dtResult As New DataTable
        dtParent.Columns.Add("filter")
        dtParent.Columns.Add("words")
        dtParent.Rows.Add({"a", "w1"})
        dtParent.Rows.Add({"b", "w2"})
        dtParent.Rows.Add({"c", "w3"})
        dtParent.Rows.Add({"k", "w4"})
        dtParent.Rows.Add({"m", "w5"})
        dtChild.Columns.Add("Filter")
        dtChild.Rows.Add("k")
        dtChild.Rows.Add("b")
        dtChild.Rows.Add("c")
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,659 questions
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 28,941 Reputation points Microsoft Vendor
    2023-06-05T02:04:41.7533333+00:00

    Hi @Mansour_Dalir ,

    You can refer to the following code.

    Dim resultTable As New DataTable("Result")
    resultTable.Columns.Add("filter")
    resultTable.Columns.Add("words")
    
    Dim query = dtParent.AsEnumerable() _
                .Join(dtChild.AsEnumerable(),
                      Function(parentRow) parentRow("filter").ToString(),
                      Function(childRow) childRow("Filter").ToString(),
                      Function(parentRow, childRow) New With {
                          .Filter = parentRow("filter"),
                          .Words = parentRow("words")
                      }) _
                .OrderBy(Function(row) row.Filter)
    
    query.Select(Function(row) resultTable.Rows.Add(row.Filter, row.Words)).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.

0 additional answers

Sort by: Most helpful