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.
}
}
}
I want to change order of gridview columns (8th to be first, first to be second, second to be third...). I am filling my gridview (which has 9 columns) with data from text file. Code is here:
public 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 = File.ReadAllLines(filePath);
List<string> ekran = new List<string>();
foreach (string line in lines)
{
var cols = line.Split(',');
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < 9; cIndex++)
{
if (cols[cIndex].Contains('_'))
{
cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
dr[cIndex] = cols[cIndex];
}
else
{
cols[cIndex] += '_';
cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
dr[cIndex] = cols[cIndex];
}
}
for (int cIndex = 0; cIndex < 9;cIndex++ )
if (dr[cIndex].ToString() == promenljiva)
tbl.Rows.Add(dr);
}
this.GridView1.DataSource = tbl;
this.GridView1.DataBind();
return tbl;
}
After that i have this:
ConvertToDataTable(filePath, 9);
This is gridview:
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
How can i do that?
Before setting the DataSource of the grid
tbl.Columns[8].SetOrdinal(0);
This will change the Ordinal property of the DataColumn inside the DataTable.DataColumnCollection in a way that the grid sees, as first column, your 9th column. Of course all other columns move up to a new index position
For further reading, it's discussed in detail here!
https://www.codeproject.com/Questions/711397/How-to-Change-order-of-columns-in-gridview
How to reorder columns in gridview dynamically
Then some add/remove column pieces with "geekwithblogs" site
http://geekswithblogs.net/dotNETvinz/archive/2009/06/03/move--autogenerate-columns-at-leftmost-part-of-the-gridview.aspx
How to add a row in the data table
Code
DataTable dt = new DataTable();
dt.Clear();
DataColumn dc = new DataColumn("day1", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("day2", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("day3", typeof(String));
dt.Columns.Add(dc);
tString[0] = "Sat,mon,tue";
tString[1] = "Fri,,wed";
tString[2] = "Thu,";
int lengthA = tString.Length;
for (int i = 0; i <= lengthA - 1; i++)
{
string s = tString[i];
string[] words = s.Split(',');
foreach (string word in words)
{
dt.Rows.Add(word);
}
}
The issue in dt.Rows.Add(word) because it is inserting a row
Expected Output
Datatable value should be
day1, day2, day3
sun,mon,tue
Fri,Wed
Thu
Hot to achieve this, can any one help me
Just create a NewRow() and then add the values to its Item indexer for each column.
for (int i = 0; i <= lengthA - 1; i++)
{
string s = tString[i];
string[] words = s.Split(',');
// here is the new row
var row = dt.NewRow();
for(int w = 0; w < words.Length; w++)
{
// set each column
row[w] = words[w];
}
// don't forget to add the Row to the Rows collection
dt.Rows.Add(row);
}
I want to basically go this is row 1, row 2, 3, 4...until the last row and add that as a new column on my datagrid table, I am not trying to find the total amount of rows.
Here is my current code (I think this is terribly wrong but this is a lot of new code):
for (int i = 0; i < table.Rows.Count; i++)
{
string rowNum = table.Rows[i].ToString();
table.Columns.Add("Book num", typeof(string), rowNum);
}
The following code will add 1 new column to your table, and then populate each row in that column with the index number of that row.
If you don't want to start with 0, just change int i = 0; to int i = 1;
table.Columns.Add("Book num", typeof(string));
int i = 0;
foreach (DataRow dr in table.Rows)
{
dr["Book num"] = i;
i++;
}
Try for total rows,
int TotalRows = 0;
for (int i = 0; i < table.Rows.Count; i++)
{
if(i == 0)
{
TotalRows = 1;
}
else
{
TotalRows + = i;
}
string rowNum = table.Rows[i].ToString();
table.Columns.Add("Book num", typeof(string), rowNum);
}
I have a GridView and I need to bind it with a dynamic Data Table.
I have a List<List<string>> and a List<List<DateTime>>.
I need a DataTable with 3 columns, namely FileName, LastAccessTimeForServer1, LastAccessTimeForServer2.
The List<List<string>> would contain 2 lists of filenames(common for both the servers), while List<List<DateTime>> would contain 2 lists of last access times (different for both the files).
Below is the code which I have tried, which doesn't make much sense to me.
Completely perplexed.
string serviceName = DropDownList1.SelectedItem.Text;
List<string> serviceNameArray = new List<string>();
for (int x = 1; x <= 2; x++)
{
if (x < 2)
{
serviceNameArray.Add(#"\\Server10" + x + #"\WebSite" + "\\" + serviceName);
}
else
{
serviceNameArray.Add(#"\\Server1" + x + #"\WebSite" + "\\" + serviceName);
}
}
List<List<string>> ultimateList = new List<List<string>>();
List<int> numList = new List<int>();
//Call the Search method
for (int y = 0; y < 2; y++)
{
ultimateList.Add(Search(serviceNameArray[y]));
}
for (int z = 0; z < 2; z++)
{
numList.Add(ultimateList[z].Count);
}
//FInd the Last Write Time for all the files.
for (int xx = 0; xx < 2; xx++)
{
listOfDateTimes.Add(new List<DateTime>());
for (int yy = 0; yy < numList[xx]; yy++)
{
listOfDateTimes[xx].Add(File.GetLastWriteTime(ultimateList[xx][yy]));
}
}
DataTable dtForGridView = new DataTable();
DataColumn dc1 = new DataColumn("File Name", typeof(string));
DataColumn dc2 = new DataColumn("LastAccessTimeForServer1", typeof(DateTime));
DataColumn dc3 = new DataColumn("LastAccessTimeForServer2", typeof(DateTime));
dtForGridView.Columns.Add(dc1);
dtForGridView.Columns.Add(dc2);
dtForGridView.Columns.Add(dc3);
for (int k = 0; k <=2; k++)
{
for (int d = 0; d < numList[k]; d++)//numList[k] will give the number of rows in each column
{
dtForGridView.Rows.Add(ultimateList[d][k], listOfDateTimes[k]);
}
}
//Binding the GridView
GridView1.DataSource = dtForGridView;
GridView1.DataBind();
The final grid should look like:
FileName LastAccessTimeForServer1 LastAccessTimeForServer1
a.txt Time1 Time2
b.txt Time3 Time4
Experts please help in finding a solution.
Any pointers will be highly appreciated.
Regards
Anurag