How to 'union' 2 or more DataTables in C#? - c#

How to 'union' 2 or more DataTables in C#?
Both table has same structure.
Is there any build-in function or should we do manually?

You are looking most likely for the DataTable.Merge method.
Example:
private static void DemonstrateMergeTable()
{
DataTable table1 = new DataTable("Items");
// Add columns
DataColumn idColumn = new DataColumn("id", typeof(System.Int32));
DataColumn itemColumn = new DataColumn("item", typeof(System.Int32));
table1.Columns.Add(idColumn);
table1.Columns.Add(itemColumn);
// Set the primary key column.
table1.PrimaryKey = new DataColumn[] { idColumn };
// Add RowChanged event handler for the table.
table1.RowChanged += new
System.Data.DataRowChangeEventHandler(Row_Changed);
// Add ten rows.
DataRow row;
for (int i = 0; i <= 9; i++)
{
row = table1.NewRow();
row["id"] = i;
row["item"] = i;
table1.Rows.Add(row);
}
// Accept changes.
table1.AcceptChanges();
PrintValues(table1, "Original values");
// Create a second DataTable identical to the first.
DataTable table2 = table1.Clone();
// Add column to the second column, so that the
// schemas no longer match.
table2.Columns.Add("newColumn", typeof(System.String));
// Add three rows. Note that the id column can't be the
// same as existing rows in the original table.
row = table2.NewRow();
row["id"] = 14;
row["item"] = 774;
row["newColumn"] = "new column 1";
table2.Rows.Add(row);
row = table2.NewRow();
row["id"] = 12;
row["item"] = 555;
row["newColumn"] = "new column 2";
table2.Rows.Add(row);
row = table2.NewRow();
row["id"] = 13;
row["item"] = 665;
row["newColumn"] = "new column 3";
table2.Rows.Add(row);
// Merge table2 into the table1.
Console.WriteLine("Merging");
table1.Merge(table2, false, MissingSchemaAction.Add);
PrintValues(table1, "Merged With table1, schema added");
}
private static void Row_Changed(object sender,
DataRowChangeEventArgs e)
{
Console.WriteLine("Row changed {0}\t{1}", e.Action,
e.Row.ItemArray[0]);
}
private static void PrintValues(DataTable table, string label)
{
// Display the values in the supplied DataTable:
Console.WriteLine(label);
foreach (DataRow row in table.Rows)
{
foreach (DataColumn col in table.Columns)
{
Console.Write("\t " + row[col].ToString());
}
Console.WriteLine();
}
}

You could try this:
public static DataTable Union (DataTable First, DataTable Second)
{
//Result table
DataTable table = new DataTable("Union");
//Build new columns
DataColumn[] newcolumns = new DataColumn[First.Columns.Count];
for(int i=0; i < First.Columns.Count; i++)
{
newcolumns[i] = new DataColumn(
First.Columns[i].ColumnName, First.Columns[i].DataType);
}
table.Columns.AddRange(newcolumns);
table.BeginLoadData();
foreach(DataRow row in First.Rows)
{
table.LoadDataRow(row.ItemArray,true);
}
foreach(DataRow row in Second.Rows)
{
table.LoadDataRow(row.ItemArray,true);
}
table.EndLoadData();
return table;
}
From here (not tested).

You could use Concat from Linq to datasets (get the free chapter of LINQ in Action) to join them and then .AsDataTable to create the table (assuming you actually want them as a DataTable)

Stumbled across this question, and Ruben Bartelink gave a great answer, but with no code. So I had to look it up elsewhere, which defeats the point of StackOverflow. Now that it's 2010, the other answers given aren't quite as viable. For reference, here's code demonstrating the CopyToDataTable() extension method. It's in VB so as to not steal the credit from Ruben if he wants to revisit the past and post a more complete answer :)
Public Function GetSchema(ByVal dbNames As IEnumerable(Of String)) As DataTable
Dim schemaTables As New List(Of DataTable)()
For Each dbName As String In dbNames
Dim cnnStr = GetConnectionString(dbName)
Dim cnn As New SqlConnection(cnnStr)
cnn.Open()
Dim dt = cnn.GetSchema("Columns")
cnn.Close()
schemaTables.Add(dt)
Next
Dim dtResult As DataTable = Nothing
For Each dt As DataTable In schemaTables
If dtResult Is Nothing Then
dtResult = dt
Else
dt.AsEnumerable().CopyToDataTable(dtResult, LoadOption.PreserveChanges)
End If
Next
Return dtResult
End Function

Try this using Linq to DataSet, must add the reference for System.Data.DataSetExtensions.dll, another approach, alternative for DataTable.Merge method).
static void Main(string[] args)
{
DoUnion();
}
private static void DoUnion()
{
DataTable table1 = GetProducts();
DataTable table2 = NewProducts();
var tbUnion = table1.AsEnumerable()
.Union(table2.AsEnumerable());
DataTable unionTable = table1.Clone();
foreach (DataRow fruit in tbUnion)
{
var fruitValue = fruit.Field<string>(0);
Console.WriteLine("{0}->{1}", fruit.Table, fruitValue);
DataRow row = unionTable.NewRow();
row.SetField<string>(0, fruitValue);
unionTable.Rows.Add(row);
}
}
private static DataTable NewProducts()
{
DataTable table = new DataTable("CitricusTable");
DataColumn col = new DataColumn("product", typeof(string));
table.Columns.Add(col);
string[] citricusFruits = { "Orange", "Grapefruit", "Lemon", "Lime", "Tangerine" };
foreach (string fruit in citricusFruits)
{
DataRow row = table.NewRow();
row.SetField<string>(col, fruit);
table.Rows.Add(row);
}
return table;
}
private static DataTable GetProducts()
{
DataTable table = new DataTable("MultipleFruitsTable");
DataColumn col = new DataColumn("product", typeof(string));
table.Columns.Add(col);
string[] multipleFruits = { "Breadfruit", "Custardfruit", "Jackfruit", "Osage-orange", "Pineapple" };
foreach (string fruit in multipleFruits)
{
DataRow row = table.NewRow();
row.SetField<string>(col, fruit);
table.Rows.Add(row);
}
return table;
}
antonio

Related

c# Randomize DataTable rows

I have a Data Table I'm using as the data source for a repeater and would like to have the results show in a random order each time it's called.
I've been able to do this while retrieving the data but wish to cache the result set before it's bound.
Is the any was to shuffle or randomise the rows of a data table before binding to the repeater?
CODE:
TreeProvider tp = new TreeProvider();
DataSet ds = new DataSet();
string sKey = "KEY";
using (CachedSection<DataSet> cs = new CachedSection<DataSet>(ref ds, 5, true, null, sKey))
{
if (cs.LoadData)
{
ds = tp.SelectNodes("", "URL", "", true, "DOCTYPE", "", "NewID()", -1, true, 5);
cs.Data = ds;
}
}
if (!DataHelper.DataSourceIsEmpty(ds))
{
rprItems.DataSource = ds.Tables[0].DefaultView;
rprItems.DataBind();
}
Any guidance is appreciated.
I ended up taking a copy of the table, adding a field and assigning a random number to each row then ordering by that row.
DataTable dt = ds.Tables[0].Copy();
if (!dt.Columns.Contains("SortBy"))
dt.Columns.Add("SortBy", typeof (Int32));
foreach (DataColumn col in dt.Columns)
col.ReadOnly = false;
Random rnd = new Random();
foreach (DataRow row in dt.Rows)
{
row["SortBy"] = rnd.Next(1, 100);
}
DataView dv = dt.DefaultView;
dv.Sort = "SortBy";
DataTable sortedDT = dv.ToTable();
rprItems.DataSource = sortedDT;
rprItems.DataBind();
You could try something like this, I know it's not pretty but:
DataTable newTable = new DataTable();
newTable.TableName = "<NewTableName>";
//Make a new Random generator
Random rnd = new Random();
while (<new table length> != <old table length>)
{
//We'll use this to make sure we don't have a duplicate row
bool rowFound = false;
//index generation
int index = rnd.Next(0, <max number of rows in old data>);
//use the index on the old table to get the random data, then put it into the new table.
foreach (DataRow row in newTable.Rows)
{
if (oldTable.Rows[index] == row)
{
//Oops, there's duplicate data already in the new table. We don't want this.
rowFound = true;
break;
}
}
if (!rowFound)
{
//add the row to newTable
newTable.Rows.Add(oldTable.Rows[index];
}
}
You'll have to use your own tables, names, and lengths of course, but this should be ok to use. If there's a lot of data, this could take a while. It's the best I can come up with, and it's untested. I'm curious to know if it works.
You could try:
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Sort");
dt.Rows.Add("TEST");
dt.Rows.Add("TEST1");
dt.Rows.Add("TEST2");
var rnd = new Random(DateTime.Now.Millisecond);
foreach (DataRow row in dt.Rows)
{
row["Sort"] = rnd.Next(dt.Rows.Count);
}
var dv = new DataView(dt);
dv.Sort = "Sort";
foreach (DataRowView row in dv)
{
Console.WriteLine(row[0]);
}
If your datatable is not too big it should do it.

Join 2 DataTables into 1 in C# [duplicate]

This question already has answers here:
how to join two datatable datas into one datatable to show in one gridview in asp.net
(4 answers)
Closed 9 years ago.
I have two identical DataTables from two different databases (but the ids are unique!). So now I want to have combine this data into a single DataTable. I have no idea what to do.
I tried the following:
DataTable one = new DataTable();
one = baza_win.pobierz_dane("SELECT...");
DataTable two = new DataTable();
two = baza_win2.pobierz_dane("SELECT...");
//DataTable sum = one + two;
DataTable sum = new DataTable();
sum.Clone(one);
sum.Merge(two,false);
But this doesn't work at sum.Clone(one);
Any ideas?
sum = one.Copy();
sum.Merge(two);
I think you need Copy instead of Clone:
DataTable one = new DataTable();
one = baza_win.pobierz_dane("SELECT...");
DataTable two = new DataTable();
two = baza_win2.pobierz_dane("SELECT...");
//DataTable sum = one + two;
DataTable sum = new DataTable();
sum.Copy(one);
sum.Merge(two,false);
copied from link
http://msdn.microsoft.com/en-us/library/fk68ew7b.aspx
duplicate of
how to join two datatable datas into one datatable to show in one gridview in asp.net
private static void DemonstrateMergeTable()
{
DataTable table1 = new DataTable("Items");
// Add columns
DataColumn column1 = new DataColumn("id", typeof(System.Int32));
DataColumn column2 = new DataColumn("item", typeof(System.Int32));
table1.Columns.Add(column1);
table1.Columns.Add(column2);
// Set the primary key column.
table1.PrimaryKey = new DataColumn[] { column1 };
// Add RowChanged event handler for the table.
table1.RowChanged +=
new System.Data.DataRowChangeEventHandler(Row_Changed);
// Add some rows.
DataRow row;
for (int i = 0; i <= 3; i++)
{
row = table1.NewRow();
row["id"] = i;
row["item"] = i;
table1.Rows.Add(row);
}
// Accept changes.
table1.AcceptChanges();
PrintValues(table1, "Original values");
// Create a second DataTable identical to the first.
DataTable table2 = table1.Clone();
// Add three rows. Note that the id column can't be the
// same as existing rows in the original table.
row = table2.NewRow();
row["id"] = 14;
row["item"] = 774;
table2.Rows.Add(row);
row = table2.NewRow();
row["id"] = 12;
row["item"] = 555;
table2.Rows.Add(row);
row = table2.NewRow();
row["id"] = 13;
row["item"] = 665;
table2.Rows.Add(row);
// Merge table2 into the table1.
Console.WriteLine("Merging");
table1.Merge(table2);
PrintValues(table1, "Merged With table1");
}
private static void Row_Changed(object sender,
DataRowChangeEventArgs e)
{
Console.WriteLine("Row changed {0}\t{1}",
e.Action, e.Row.ItemArray[0]);
}
private static void PrintValues(DataTable table, string label)
{
// Display the values in the supplied DataTable:
Console.WriteLine(label);
foreach (DataRow row in table.Rows)
{
foreach (DataColumn col in table.Columns)
{
Console.Write("\t " + row[col].ToString());
}
Console.WriteLine();
}
}
try the following... CLONE the first table so it has proper structure, THEN merge two into it.
DataTable sum = one.Clone()
sum.Merge(two,false);

How to assign a value to the original datarow after I am iterating over a temporary datatable

I am trying to explain what I need to do.
As you can see in the second foreach, I am iterating over the temporary data table, but I need to set a value for the same row in the original data tablerow.
For example:
_uc090_WingsIntegrationDataSet.WingsBookingInterface[0]["property"] = x;
What I dont know how to implement is how to find that row and set the property, I saw the LoadRow method but I never used it before.
DataTable tempTable = _uc090_WingsIntegrationDataSet.WingsBookingInterface.Clone();
DataRow[] datarows = _uc090_WingsIntegrationDataSet.WingsBookingInterface.Select("REFMDossierID = " + refmDossierId);
if (datarows.Length > 0)
{
foreach (DataRow dr in datarows)
{
tempTable.ImportRow(dr);
}
}
//2. foreach master row
foreach (UC090_WingsIntegrationDataSet.WingsBookingInterfaceRow row in tempTable.Rows)
You can find the row using Rows.Find(), but it requires that a PrimaryKey be set on at least one column in your DataTable.
As far as loading new data, you can use LoadDataRow() which will update existing rows (if a primary key is supplied) or insert new data if any matching datatypes are found.
Please take a look at the following example using untyped datasets:
DataSet dataSet = new DataSet("MyDataSet");
DataTable dataTable = dataSet.Tables.Add("JavaScriptLibraries");
DataColumn[] dataColumns =
new[] {
new DataColumn("Id", typeof(Int32))
{
AutoIncrement = true,
AllowDBNull = false,
AutoIncrementSeed = 1
},
new DataColumn("Name", typeof(String))
};
dataTable.Columns.AddRange(dataColumns);
dataTable.PrimaryKey = new[] { dataTable.Columns["Id"] };
DataRow dataRow1 = dataTable.NewRow();
dataRow1["Name"] = "jQuery";
dataTable.Rows.Add(dataRow1);
DataRow dataRow2 = dataTable.NewRow();
dataRow2["Name"] = "MooTools";
dataTable.Rows.Add(dataRow2);
// Copy the dataset
DataSet tempDataSet = dataSet.Clone();
DataTable tempDataTable = tempDataSet.Tables["JavaScriptLibraries"];
DataRow[] tempRows = dataSet.Tables["JavaScriptLibraries"].Select("Name = 'jQuery'");
// Import rows to copy of table
foreach (var tempRow in tempRows)
{
tempDataTable.ImportRow(tempRow);
}
foreach (DataRow tempRow in tempDataTable.Rows)
{
// Find existing row by PK, then update it
DataRow originalRow = dataTable.Rows.Find(tempRow["Id"]);
originalRow["Name"] = "Updated Name";
}
// Load new data using LoadDataRow()
object[] newRow = new[] { null, "New Row" };
dataTable.BeginLoadData();
dataTable.LoadDataRow(newRow, true);
dataTable.EndLoadData();

How to add New Column with Value to the Existing DataTable?

I have One DataTable with 5 Columns and 10 Rows.
Now I want to add one New Column to the DataTable and I want to assign DropDownList value to the New Column.
So the DropDownList value should be added 10 times to the New Column.
How to do this?
Note: Without using FOR LOOP.
For Example: My Existing DataTable is like this.
ID Value
----- -------
1 100
2 150
Now I want to add one New Column "CourseID" to this DataTable.
I have One DropDownList. Its selected value is 1.
So My Existing Table should be like below:
ID Value CourseID
----- ------ ----------
1 100 1
2 150 1
How to do this?
Without For loop:
Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))
newColumn.DefaultValue = "Your DropDownList value"
table.Columns.Add(newColumn)
C#:
System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);
Add the column and update all rows in the DataTable, for example:
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Name", typeof(string)));
for (Int32 i = 1; i <= 10; i++) {
DataRow row = tbl.NewRow();
row["ID"] = i;
row["Name"] = i + ". row";
tbl.Rows.Add(row);
}
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
tbl.Columns.Add(newCol);
foreach (DataRow row in tbl.Rows) {
row["NewColumn"] = "You DropDownList value";
}
//if you don't want to allow null-values'
newCol.AllowDBNull = false;
//Data Table
protected DataTable tblDynamic
{
get
{
return (DataTable)ViewState["tblDynamic"];
}
set
{
ViewState["tblDynamic"] = value;
}
}
//DynamicReport_GetUserType() function for getting data from DB
System.Data.DataSet ds = manage.DynamicReport_GetUserType();
tblDynamic = ds.Tables[13];
//Add Column as "TypeName"
tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));
//fill column data against ds.Tables[13]
for (int i = 0; i < tblDynamic.Rows.Count; i++)
{
if (tblDynamic.Rows[i]["Type"].ToString()=="A")
{
tblDynamic.Rows[i]["TypeName"] = "Apple";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "B")
{
tblDynamic.Rows[i]["TypeName"] = "Ball";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "C")
{
tblDynamic.Rows[i]["TypeName"] = "Cat";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "D")
{
tblDynamic.Rows[i]["TypeName"] = "Dog;
}
}

How to check if a record is already present in the DataView? C#

I have a DataView which has two columns: ContactID, and Name
How can I check if a particular ContactID is already existing in the DataView?
Have you had a look at DataView.FindRows Method or maybe DataView.Find Method
The DataView has a method called FindRows, this can be used to search for a specific contactID, for example...
var table = new DataTable();
var column = new DataColumn("Id", typeof (int));
table.Columns.Add(column);
table.PrimaryKey = new[] {column}; // Unique Constraint
var row = table.NewRow();
row["Id"] = 100;
table.Rows.Add(row);
row = table.NewRow();
row["Id"] = 200;
table.Rows.Add(row);
var view = new DataView(table) { ApplyDefaultSort = true };
var rows = view.FindRows(200);
foreach(var r in rows)
{
Console.WriteLine(r["Id"]);
}
Use the Following code to Find the row in the Dataview
//Your original Table Which consist of Data
DataTable dtProducts = new DataTable();
//Add the DataTable to DataView
DataView ProductDataView = new DataView(dtProducts);
ProductDataView.RowFilter = "";
ProductDataView.Sort = "ProdId";
int recordIndex = -1;
//In the Find Row Method pass the Column
//value which you want to find
recordIndex = ProductDataView.Find(1);
if (recordIndex > -1)
{
Console.WriteLine("Row Found");
}

Categories