Skip to content

Instantly share code, notes, and snippets.

@ramazanpolat
Created September 20, 2014 23:28
Show Gist options
  • Save ramazanpolat/2b6b6b677743c4358930 to your computer and use it in GitHub Desktop.
Save ramazanpolat/2b6b6b677743c4358930 to your computer and use it in GitHub Desktop.
public class MoUtils
{
private static readonly Random random = new Random();
public DataTable MergeDataTable(DataTable dt1, DataTable dt2)
{
DataTable dtMerged = new DataTable();
foreach (DataColumn dc in dt1.Columns)
{
dtMerged.Columns.Add(dc.ColumnName, dc.DataType);
}
foreach (DataColumn dc in dt2.Columns)
{
dtMerged.Columns.Add(dc.ColumnName, dc.DataType);
}
int rowMinCount = Math.Min(dt1.Rows.Count, dt2.Rows.Count);
int rowMaxCount = Math.Max(dt1.Rows.Count, dt2.Rows.Count);
object[] itemArray = new object[dtMerged.Columns.Count];
for (int i = 0; i < rowMaxCount; i++)
{
DataRow dr = dtMerged.NewRow();
object[] rowValues = MergeItemArray(ItemArrayOfDataTable(dt1, i), ItemArrayOfDataTable(dt2, i));
for (int j = 0; j < rowValues.Length; j++)
{
dr[j] = rowValues[j];
}
dtMerged.Rows.Add(dr);
}
return dtMerged;
}
public object[] MergeItemArray(object[] itemArray1, object[] itemArray2)
{
int count1 = itemArray1.Length;
int count2 = itemArray2.Length;
object[] mergedItemArray = new object[count1 + count2];
int arrayIndex = 0;
for (int i = 0; i < count1; i++)
{
mergedItemArray[arrayIndex] = itemArray1[i];
arrayIndex++;
}
for (int i = 0; i < count2; i++)
{
mergedItemArray[arrayIndex] = itemArray2[i];
arrayIndex++;
}
return mergedItemArray;
}
public object[] ItemArrayOfDataTable(DataTable dt, int rowIndex)
{
object[] resultArray = new object[dt.Columns.Count];
if (rowIndex < dt.Rows.Count)
{
resultArray = dt.Rows[rowIndex].ItemArray;
}
else
{
resultArray = dt.NewRow().ItemArray;
}
return resultArray;
}
public DataTable CreateDataTable(int rowCount, params string[] columnNames)
{
// Create an empty table.
DataTable table = new DataTable("Table1");
// Add two columns to the table.
foreach (string name in columnNames)
{
table.Columns.Add(name);
}
DataRow row = null;
for (int i = 0; i < rowCount; i++)
{
row = table.NewRow();
foreach (string columnName in columnNames)
{
row[columnName] = random.Next(100)+ 1;
}
table.Rows.Add(row);
}
return table;
}
public List<string> StringifyDataTable(DataTable dt)
{
List<string> stringfy = new List<string>();
string str="";
foreach (DataColumn dc in dt.Columns)
{
str += dc.ColumnName +" |";
}
stringfy.Add(str);
stringfy.Add("-------------------------");
foreach (DataRow dr in dt.Rows)
{
str = "";
foreach (var item in dr.ItemArray)
{
str += item.ToString() + " |";
}
stringfy.Add(str);
}
return stringfy;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment