Example:
REM:Department Datatable
Department.Columns.Add("DepartmentId")
Department.Columns.Add("Name")
Dim dr As DataRow = Department.NewRow()
dr("DepartmentId") = "1"
dr("Name") = "HR"
Department.Rows.Add(dr)
dr = Department.NewRow()
dr("DepartmentId") = "2"
dr("Name") = "ADMIN"
Department.Rows.Add(dr)
dr.AcceptChanges()
' RESULT
' DepartMentId Name
' ---------------------------
' 1: HR
' 2: ADMIN
' Employee Datatable
Employee.Columns.Add("EmployeeID")
Employee.Columns.Add("EmpName")
Employee.Columns.Add("DepartmentId")
dr = Employee.NewRow()
dr("EmployeeID") = "1"
dr("EmpName") = "Peter"
dr("DepartmentId") = "2"
Employee.Rows.Add(dr)
dr = Employee.NewRow()
dr("EmployeeID") = "2"
dr("EmpName") = "John"
dr("DepartmentId") = "2"
Employee.Rows.Add(dr)
Employee.AcceptChanges()
dr = Employee.NewRow()
dr("EmployeeID") = "3"
dr("EmpName") = "John"
dr("DepartmentId") = "2"
Employee.Rows.Add(dr)
Employee.AcceptChanges()
'RESULT
' EmployeeID EmpName DepartmentId
' 1 Peter 2
' 2 John 2
' 3 John 2
Inner Join linq
Dim NewDataTable As DataTable = New DataTable()
'Inner Join linq
Dim result = From EMP In Employee.AsEnumerable()
Join DEP In Department.AsEnumerable()
On DEP.Field(Of String)("DepartmentId") Equals EMP.Field(Of String)("DepartmentId")
Let objectarray = New Object() {EMP.Field(Of String)("EmpName"), DEP.Field(Of String)("Name")} Select objectarray
NewDataTable = New DataTable
NewDataTable.Columns.Add("Name", GetType(String))
NewDataTable.Columns.Add("EmpName", GetType(String))
For Each array In result
newDataTable.Rows.Add(array)
Next
Inner Join with where Condition
result = From EMP In Employee.AsEnumerable()
Join DEP In Department.AsEnumerable()
On DEP.Field(Of String)("DepartmentId") Equals EMP.Field(Of String)("DepartmentId") Where EMP.Field(Of String)("EmpName") = "Peter"
Let objectarray = New Object() {EMP.Field(Of String)("EmpName"), DEP.Field(Of String)("Name")} Select objectarray
NewDataTable = New DataTable
NewDataTable.Columns.Add("Name", GetType(String))
NewDataTable.Columns.Add("EmpName", GetType(String))
For Each array In result
NewDataTable.Rows.Add(array)
Next
Result:Download:
LINQ Sample Project
Youtube Link:
0 Comments