Solved

Datatable - split into multiple data tables.

Posted on 2016-11-02
5
33 Views
Last Modified: 2016-11-07
I have a datatable, and say it contains data for a list of cars.   There are multiple records per car.  The VIN column identifies the data per car.  It's ordered by VIN.   Is there a way to easily split out the set of records per car into separate datatables?   So, if I had 6 cars worth of data, I need 6 separate data tables created from the original datatable.
0
Comment
Question by:HLRosenberger
5 Comments
 
LVL 18

Expert Comment

by:Anil Golamari
ID: 41870409
You can actually write a linq query using group by on the car type or just each car and then use 'copytodatable' method to write data into different tables. Below link's should give you an idea of what that can be done. If you can provide some sample data I can try to provide a working sample.split in vb.net
C#
0
 
LVL 33

Expert Comment

by:it_saige
ID: 41870560
In other words:
Imports System.Runtime.CompilerServices
Imports System.ComponentModel

Module Module1
	Sub Main()
		Dim data = (From i In Enumerable.Range(0, 20) Select New With {.ID = i, .Name = String.Format("Name{0}", i), .LastSaleDate = DateTime.Now.AddMonths(-(9 * i)), .VIN = If(i Mod 6 = 0, Guid.Parse("59c0743b-4cb7-466a-a069-f3be4c9ca434"), If(i Mod 5 = 0, Guid.Parse("e0f86c79-c008-480a-9cd1-7562084ebe56"), If(i Mod 4 = 0, Guid.Parse("cef55dd8-25a2-4949-92aa-3fbf1e50a192"), If(i Mod 3 = 0, Guid.Parse("a1b2f20f-6248-460e-a939-205334029266"), If(i Mod 2 = 0, Guid.Parse("f485afc0-e994-40ef-b8a1-83e2b8af330d"), Guid.Parse("6f43bb8b-29b9-4c83-89a0-6820bbab9815"))))))}).ConvertToDataTable()
		Dim sets = data.Rows.Cast(Of DataRow).GroupBy(Function(r) r("VIN")).Select(Function(g) g.CopyToDataTable())

		For Each [set] In sets
			Console.WriteLine("Demographics for VIN: {0}", [set].Rows.Cast(Of DataRow).First()("VIN"))
			Console.WriteLine("Sold {0} times before this year.", [set].Rows.Cast(Of DataRow).Where(Function(r) DateTime.Parse(r("LastSaleDate")) < DateTime.Now.AddYears(-1)).Count())
			Console.WriteLine("Sold {0} times this year.", [set].Rows.Cast(Of DataRow).Where(Function(r) DateTime.Parse(r("LastSaleDate")).Year.Equals(DateTime.Now.Year)).Count())
			Console.WriteLine()
		Next
		Console.ReadLine()
	End Sub
End Module

Module Extensions
	<Extension()> _
	Public Function ConvertToDataTable(Of T)(ByVal source As IEnumerable(Of T)) As DataTable
		Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
		Dim table As DataTable = New DataTable()

		For i As Integer = 0 To properties.Count - 1
			Dim [property] As PropertyDescriptor = properties(i)
			If [property].PropertyType.IsGenericType AndAlso [property].PropertyType.GetGenericTypeDefinition().Equals(GetType(Nullable)) Then
				table.Columns.Add([property].Name, [property].PropertyType.GetGenericArguments()(0))
			Else
				table.Columns.Add([property].Name, [property].PropertyType)
			End If
		Next

		Dim values(properties.Count - 1) As Object
		For Each item As T In source
			For i As Integer = 0 To properties.Count - 1
				values(i) = properties(i).GetValue(item)
			Next
			table.Rows.Add(values)
		Next

		Return table
	End Function
End Module

Open in new window


Produces the following output -Capture.JPG
-saige-
0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 41870591
Here is some code that will give you what you are looking for.
Public Class Form1

    Dim MyDataTable As New DataTable()

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        '' Test Data
        Dim dc = New DataColumn("VIN", GetType(String))
        MyDataTable.Columns.Add(dc)
        dc = New DataColumn("Manufacturer", GetType(String))
        MyDataTable.Columns.Add(dc)
        dc = New DataColumn("Owner", GetType(String))
        MyDataTable.Columns.Add(dc)

        Dim row = MyDataTable.NewRow()
        row(0) = "A123"
        row(1) = "Ford"
        row(2) = "John Smith"
        MyDataTable.Rows.Add(row)

        row = MyDataTable.NewRow()
        row(0) = "B123"
        row(1) = "Ford"
        row(2) = "John Smith"
        MyDataTable.Rows.Add(row)

        row = MyDataTable.NewRow()
        row(0) = "A123"
        row(1) = "Ford"
        row(2) = "Tom Smith"
        MyDataTable.Rows.Add(row)

        row = MyDataTable.NewRow()
        row(0) = "B123"
        row(1) = "Ford"
        row(2) = "John Smith"
        MyDataTable.Rows.Add(row)

        row = MyDataTable.NewRow()
        row(0) = "B123"
        row(1) = "Ford"
        row(2) = "Henry Smith"
        MyDataTable.Rows.Add(row)

        row = MyDataTable.NewRow()
        row(0) = "Z123"
        row(1) = "Ford"
        row(2) = "Alice Jones"
        MyDataTable.Rows.Add(row)

        DataGridView1.DataSource = MyDataTable

    End Sub

    Dim dTables As New List(Of DataTable)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        '' Linq query to split the original DataTable by VIN number
        dTables = (From dt In MyDataTable.AsEnumerable()
                   Group dt By vbInformation = dt.Field(Of String)("VIN") Into carGroup = Group
                   Select carGroup.CopyToDataTable()).ToList()

        '' Show the results in there own DataGridView
        DataGridView2.DataSource = dTables(0)
        DataGridView3.DataSource = dTables(1)
        DataGridView4.DataSource = dTables(2)

    End Sub

End Class

Open in new window

The results of the code isResults
0
 
LVL 1

Accepted Solution

by:
HLRosenberger earned 0 total points
ID: 41870953
I ended up using a DataView to filter and order a subset of rows in the DataTable.  Then I convert the DataView to a new DataTable.  Like,  this:


Dim dv As New DataView(dtStandardsUsed, "id = " & LocalID, "id", DataViewRowState.OriginalRows)
Dim dt As DataTable = dv.ToTable
0
 
LVL 1

Author Closing Comment

by:HLRosenberger
ID: 41876884
This work and is easy to implement.
0

Featured Post

The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
HTML - Color not displaying correctly in EMAIL. 6 49
vb.net class 3 21
SSIS Feed MS SQL Server Stored procedure with loop 4 34
JSON Deserialize issue 6 26
The debugging module of the VB 6 IDE can be accessed by way of the Debug menu item. That menu item can normally be found in the IDE's main menu line as shown in this picture.   There is also a companion Debug Toolbar that looks like the followin…
If you have ever used Microsoft Word then you know that it has a good spell checker and it may have occurred to you that the ability to check spelling might be a nice piece of functionality to add to certain applications of yours. Well the code that…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…

789 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question