C# .. DataTable Merge

Joined
Jul 9, 2023
Messages
25
Reaction score
0
Hello

I am trying to combine different DataTables.
DataTable--1 ==> Matrix : 3row * 4column ==> DataTable is created.
삭제11.png


DataTable--2 ===> Matrix : 3row * 4column ==> DataTable is created.
삭제22.png



I don't know how to join the different DataTable--1 and DataTable--2 that have been created.
===> Matrix : 3row * 8column

삭제33.png


===> How do you join DataTables in C#?

Awaiting your reply.
Thank you
 
Joined
Jul 4, 2023
Messages
366
Reaction score
41
Did you try use DataTable.Merge method?
Something like this way e.g.

C#:
using System;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dataTable1 = new DataTable();
            dataTable1.Columns.Add("Name", typeof(string));
            dataTable1.Columns.Add("Age", typeof(int));
            dataTable1.Columns.Add("School", typeof(string));

            dataTable1.Rows.Add("Alex", 21, "Princeton");
            dataTable1.Rows.Add("James", 24, "Harvard");
            dataTable1.Rows.Add("Kevin", 23, "Yale");

            DataTable dataTable2 = new DataTable();
            dataTable2.Columns.Add("Name", typeof(string));
            dataTable2.Columns.Add("Age", typeof(int));
            dataTable2.Columns.Add("School", typeof(string));

            dataTable2.Rows.Add("Joel", 20, "Columbia");
            dataTable2.Rows.Add("Gregory", 25, "Stanford");
            dataTable2.Rows.Add("Henry", 22, "California");


            // Merge dataTable2 into dataTable1
            dataTable1.Merge(dataTable2);

            // Display the merged DataTable
            foreach (DataColumn column in dataTable1.Columns)
                Console.Write(column.ColumnName + "\t\t");

            Console.WriteLine("\n" + (new string('-', 45)));

            foreach (DataRow row in dataTable1.Rows) {
                foreach (var item in row.ItemArray)
                    Console.Write(item + "\t\t");
                Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}

DataTable.Merge.png
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top