How can I compare the 2 dataTable in c#
For example
dataTable1
a,a,a,a,1,a,a,a,a,a
a,a,a,a,1,a,a,a,a,a
a,a,a,a,2,a,a,a,a,a
a,a,a,a,2,a,a,a,a,a
a,a,a,a,3,a,a,a,a,a
dataTable2
b,b,b,b,1,b,b,b,b,b
b,b,b,b,1,b,b,b,b,b
b,b,b,b,1,b,b,b,b,b
b,b,b,b,2,b,b,b,b,b
b,b,b,b,2,b,b,b,b,b
How do I run the 1st row in dataTable1 [5] which is = 1, if dataTable2 [5] also consists 1 then print out the line. Continue until finish. Then Continue loop to second one in dataTable1 check with dataTable2
Here is my code
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CompareLinuxWithWindow
{
class Program
{
static void Main(string[] args)
{
DataTable dt1 = ConvertToDataTable(#"C:\Users\manchunl\Desktop\Sample1.txt", 10);
DataTable dt2 = ConvertToDataTable2(#"C:\Users\manchunl\Desktop\Sample2.txt", 10);
foreach (DataRow row in dt1.AsEnumerable())
{
string temp_dt1 = "";
string[] words = temp_dt1.Split(',');
string.Join(",", row.ItemArray.Select(x => x.ToString()));
temp_Linux = (string.Join(",", row.ItemArray.Select(x => x.ToString())));
}
foreach (DataRow row in dt2.AsEnumerable())
{
string temp_dt2 = "";
string.Join(",", row.ItemArray.Select(x => x.ToString()));
temp_dt2 = (string.Join(",", row.ItemArray.Select(x => x.ToString())));
}
Console.WriteLine();
Console.WriteLine("Press enter to exit.");
Console.Read();
}
public static DataTable ConvertToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
string[] lines = System.IO.File.ReadAllLines(filePath);
foreach (string line in lines)
{
var cols = line.Split(null);
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < numberOfColumns; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
}
return tbl;
}
public static DataTable ConvertToDataTable2(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
string[] lines = System.IO.File.ReadAllLines(filePath);
foreach (string line in lines)
{
var cols = line.Split(',');
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < numberOfColumns; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
}
return tbl;
}
}
}
You can try using the loop as below, please pay attention to comments as those are important
// assumption is that both dt1 and dt2 has same number of rows
// otherise while accessing dt2 we can get index out of range exception
for (int i = 0; i < dt1.Rows.Count; i++)
{
DataRow dr1 = dt1.Rows[i];
DataRow dr2 = dt2.Rows[i];
// accessing the column below would return a system.object variable,
// need to convert it to the right type using one of the convert calls, e.g. Convert.ToInt16(dr1["ColumnName"])
if (dr1["ColumnName"] == dr2["ColumnName"])
{
// do whatever you want to do here
}
}
You can return the data table which will be the difference of two input data table and later you can perform operations on the resulting data table.
CODE
/// <summary>
/// Compare two DataTables and return a DataTable with DifferentRecords
/// </summary>
/// <param name="FirstDataTable">FirstDataTable</param>
/// <param name="SecondDataTable">SecondDataTable</param>
/// <returns>DifferentRecords</returns>
public DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable)
{
//Create Empty Table
DataTable ResultDataTable = new DataTable("ResultDataTable");
//use a Dataset to make use of a DataRelation object
using (DataSet ds = new DataSet())
{
var dataTable = new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() };
dataTable[0].TableName = "FirstTable";
dataTable[1].TableName = "SecondTable";
//Add tables
ds.Tables.AddRange(dataTable);
//Get Columns for DataRelation
DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count];
for (int i = 0; i < firstColumns.Length; i++)
{
firstColumns[i] = ds.Tables[0].Columns[i];
}
DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count];
for (int i = 0; i < secondColumns.Length; i++)
{
secondColumns[i] = ds.Tables[1].Columns[i];
}
//Create DataRelation
DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false);
ds.Relations.Add(r1);
DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false);
ds.Relations.Add(r2);
//Create columns for return table
for (int i = 0; i < FirstDataTable.Columns.Count; i++)
{
ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName,
FirstDataTable.Columns[i].DataType);
}
//If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable.
ResultDataTable.BeginLoadData();
foreach (DataRow parentrow in ds.Tables[0].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r1);
if (childrows == null || childrows.Length == 0)
{
ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
}
}
//If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable.
foreach (DataRow parentrow in ds.Tables[1].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r2);
if (childrows == null || childrows.Length == 0)
ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
}
ResultDataTable.EndLoadData();
}
return ResultDataTable;
}
You need to first loop on the first data table
Then get row at specific index
Check whether current row exist in second data table
Get row from second data table at same index.
Read the column value from row to string variable.
Check if both value from both row are equal or not.
DataTable dt1 = ConvertToDataTable(#"C:\Users\manchunl\Desktop\Sample1.txt", 10);
DataTable dt2 = ConvertToDataTable2(#"C:\Users\manchunl\Desktop\Sample2.txt", 10);
for (int i = 0; i < dt1.Rows.Count; i++)
{
DataRow dr1 = dt1.Rows[i];
if (dt2.Rows.Count > i)
{
DataRow dr2 = dt2.Rows[i];
string value1 = Convert.ToString(dr1["Column5"]);
string value2 = Convert.ToString(dr2["Column5"]);
if (!string.IsNullOrEmpty(value1) && !string.IsNullOrEmpty(value2) && value1 == value2)
{
Console.WriteLine(value1);
}
else
{
//Do code when no matched.
}
}
}
So far I have tried to convert DataTable to String as follow:-
public static string convertDataTableToString(DataTable dataTable)
{
string data = string.Empty;
int rowsCount = dataTable.Rows.Count;
for (int i = 0; i < rowsCount; i++)
{
DataRow row = dataTable.Rows[i];
int columnsCount = dataTable.Columns.Count;
for (int j = 0; j < columnsCount; j++)
{
data += dataTable.Columns[j].ColumnName + "~" + row[j];
if (j == columnsCount - 1)
{
if (i != (rowsCount - 1))
data += "$";
}
else
data += "|";
}
}
return data;
}
Now I want to convert returned string into DataTable again.
You can use String.Split to break your string into rows and cells. If the column setup is always the same (as it should be), then you can simply add the columns on your first iteration through the cells.
Here's a simple example:
public static DataTable convertStringToDataTable(string data)
{
DataTable dataTable = new DataTable();
bool columnsAdded = false;
foreach(string row in data.Split('$'))
{
DataRow dataRow = dataTable.NewRow();
foreach(string cell in row.Split('|'))
{
string[] keyValue = cell.Split('~');
if (!columnsAdded)
{
DataColumn dataColumn = new DataColumn(keyValue[0]);
dataTable.Columns.Add(dataColumn);
}
dataRow[keyValue[0]] = keyValue[1];
}
columnsAdded = true;
dataTable.Rows.Add(dataRow);
}
return dataTable;
}
Alternatively you could get a list of all columns prior to the loop, but this way is likely easier for your purpose.
I am comparing two Datatables and built a new table
I want to sort the values in the new table since it has -ve values(if not converted to decimal then -ve sign will not be considered)
I want to convert it to Decimal type from string and return the table for sorting. I am getting error as input string is not in correct format how solve this?And sort -ve values in Asc order
private static DataTable CompareTwoDataTable(DataTable table1, DataTable table2)
{
DataTable table3 = new DataTable();
DataRow dr = null;
string filterExp = string.Empty;
for (int i = 0; i < table1.Rows.Count; i++)
{
string col = table1.Rows[i]["Parameter Name"].ToString();
if (table2.Columns.Contains(col))
{
if (!table3.Columns.Contains(col))
{
table3.Columns.Add(col, typeof(string));
filterExp = filterExp + col + " asc ,";
}
for (int j = 0; j < table2.Rows.Count; j++)
{
if (table3.Rows.Count != table2.Rows.Count)
{
dr = table3.NewRow();
table3.Rows.Add(dr);
}
table3.Rows[j][col] = (table2.Rows[j][col].ToString());
}
}
}
DataView dv = new DataView(table3);
filterExp = filterExp.TrimEnd(',');
dv.Sort = filterExp;
table3 = dv.ToTable();
return table3;
}
`
private static DataTable CompareTwoDataTable(DataTable table1, DataTable table2)
{
DataTable table3 = new DataTable();
DataRow dr = null;
string filterExp = string.Empty;
for (int i = 0; i < table1.Rows.Count; i++)
{
string col = table1.Rows[i]["Par Name"].ToString();
if (table2.Columns.Contains(col))
{
if (!table3.Columns.Contains(col))
{
table3.Columns.Add(col, typeof(double));
filterExp = filterExp + col + " asc ,";
}
for (int j = 0; j < table2.Rows.Count; j++)
{
if (table3.Rows.Count != table2.Rows.Count)
{
dr = table3.NewRow();
table3.Rows.Add(dr);
}
table3.Rows[j][col] = table2.Rows[j][col];
}
}
}
`
So i'm making a program to Audit some of our workers randomly. And i'm trying to make a program to scan our Access DB and pull a percentage of orders. But i want to randomly select the orders, i dont want just the top 5% or something.
static DataTable RandomSelect(double errPercentage,string User)
{
OleDbConnection conn = new OleDbConnection(strAccessConn);
string query = "SELECT ControlNumber FROM Log WHERE User ='" + User + "' AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered');";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
DataTable dt = new DataTable();
DataTable dtRandomRows = new DataTable();
try
{
adapter.Fill(dt);
//dtRandomRows = dt.Clone();
Random rDom = new Random();
int i = 0;
for (int ctr = 1; ctr <= dt.Rows.Count; ctr++)
{
i = rDom.Next(1, dt.Rows.Count);
//dtRandomRows.Rows.Add(dt.Rows[i]);
dtRandomRows.ImportRow(dt.Rows[i]);
}
dtRandomRows.AcceptChanges();
}
catch (OleDbException ex)
{
}
return dtRandomRows;
}
The code above works, but it randomly selects rows from the entire table of the ControlNumbers (orders) and puts them all into dtRandomRows. However, i just want this to select the 'errPercentage' or rows randomly...any thoughts?
Random rand = new Random();
// Mark every row as not selected yet.
int[] nonSelectedRows = new int[dt.Rows.Count];
for(int i = 0; i < dt.Rows.Count; i++)
nonSelectedRows[i] = 1;
int numSelected = 0;
int numLeft = dt.Rows.Count;
int targetNum = dt.Rows.Count * errPercentage;
while(numSelected < targetNum)
{
for (int row = 0; row < dt.Rows.Count; row++)
{
// Each record has a 1/numleft chance of getting selected.
boolean isSelected = rand.Next(numLeft) == 0;
// Check to make sure it hasn't already been selected.
if(isSelected && nonSelectedRows[row] > 0)
{
dtRandomRows.ImportRow(dt.Rows[row]);
nonSelectedRows[row] = -1; // Mark this row as selected.
numSelected++;
numLeft--;
}
// We've already found enough to match our targetNum.
if(numSelected >= targetNum)
break;
}
}
I am using the code below to sort my data the program runs with out any isses but the data in the rows is not being sorted.. and cant find a reason why this would be the case.
DataTable extractedData = new DataTable();
//data added to datatable extractedData
DataView dv = new DataView();
dv =extractedData.AsDataView();
dv.Sort = dv.Table.Columns[10].ColumnName + " DESC";
extractedData = dv.Table;
This code below is using apose.slides to add code into a presentation table.
string val = "";
int col = 0;
int row = 0;
for (int i = 1; i < table.Rows.Count; i++)
{
for (int j = 0; j < table.Columns.Count; j++)
{
if (j == 0)
{
val = extractedData.Rows[row][valuesUsed[col]].ToString();
string[] removeQuestion = val.Split('[', ']');
val = removeQuestion[1];
}
else
{
val = extractedData.Rows[row][valuesUsed[col]].ToString();
if (val == "-" || val == "")
{
val = extractedData.Rows[row][valuesUsed[col]].ToString();
}
else
{
val = Convert.ToString(Math.Round(Convert.ToDouble(extractedData.Rows[row][valuesUsed[col]]), MidpointRounding.AwayFromZero));
}
}
table[j, i].TextFrame.Text = val;
col++;
}
row++;
col = 0;
}
This will work :-
DataView dv = extractedData.DefaultView;
dv.Sort = extractedData.Columns[10].ColumnName + " DESC";
You were required to make the DataView the DataTables default view inorder for it to work.
Here's a link you should check out too.
http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx
Change the last line of your code to dv.toTable() instead of dv.Table.
DataTable extractedData = new DataTable();
//data added to datatable extractedData
DataView dv = new DataView();
dv = extractedData.DefaultView;
dv.Sort = "ColumnName DESC"; //mention exact name of your column
//or else
//dv.Sort = extractedData.Columns[9].ColumnName + " DESC";
extractedData = dv.toTable(); //Instead of dv.Table;
For information go through this link.