/*
已知 DataTable (first和 second) , 两个DataTable中都有一列 ID,并且值唯一
要求:组织一个新的DataTable ,满足以下:
如果 first 存在于 second 中则更新first的Name列为second的Name
如果不存在则删除该行
如果 second 的行不存在于first 就添加到 first中
*/
using System;
using System.Collections;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Demo d = new Demo();
d.Run();
}
}
class Demo
{
DataTable first, second;
public void Run()
{
int i, j;
first = new DataTable();
first.Columns.Add("ID");
first.Columns.Add("Name");
DataRow dr;
for (i = 1; i < 100; i++)
{
dr = first.NewRow();
dr[0] = i;
dr[1] = i;
first.Rows.Add(dr);
}
Console.Write("\n\nold first:\n");
foreach (DataRow outRow in first.Rows)
{
Console.Write(outRow[0].ToString() + " | " + outRow[1].ToString() + "\n");
}
second = first.Clone();
this.AddToSecond(1, 00001);
this.AddToSecond(2, 20000);
this.AddToSecond(5, 55555);
this.AddToSecond(100,00100);
this.AddToSecond(150, 00150);
Console.Write("\n\nold second:\n");
foreach (DataRow outRow in second.Rows)
{
Console.Write(outRow[0].ToString() + " | " + outRow[1].ToString() + "\n");
}
int len1 = first.Rows.Count;
int len2 = second.Rows.Count;
ArrayList DeleteRows = new ArrayList();
ArrayList NewRows = new ArrayList();
for (i = 0, j = 0; i < len1 && j < len2; )
{
string se = second.Rows[j][0].ToString();
string fi = first.Rows[i][0].ToString();
int compar = se.CompareTo(fi);
if (compar > 0) //second > first
{
DeleteRows.Add(i++);//已经删除的
}
else if (compar == 0)
{
first.Rows[i][1] = second.Rows[j][1].ToString() + "(修改)";
i++;
j++;
}
else
{
NewRows.Add(j++); //新加的
}
}
if (i < len1)
{
//如果第一个没有遍历完,说明剩下的都是要删除的
for (; i < len1; i++)
{
DeleteRows.Add(i);
}
}
else if (j < len2)
{
//如果第二个没有遍历完,说明剩下的都是要添加的
for (; j < len2; j++)
{
NewRows.Add(j);
}
}
//delete
int[] DeleteArray = (int[])DeleteRows.ToArray(typeof(int));
i = DeleteArray.Length - 1;
while (i > -1)
{
//从后面开始删
first.Rows.RemoveAt(DeleteArray[i]);
i--;
}
//add new
int[] NewArray = (int[])NewRows.ToArray(typeof(int));
for (i = 0; i < NewArray.Length; i++)
{
DataRow drNew = first.NewRow();
drNew[0] = second.Rows[NewArray[i]][0];
drNew[1] = second.Rows[NewArray[i]][1].ToString() + "(新增)";
first.Rows.Add(drNew);
}
Console.Write("\n\nresult second:\n");
foreach (DataRow outRow in first.Rows)
{
Console.Write(outRow[0].ToString() + " | " + outRow[1].ToString() + "\n");
}
Console.Read();
}
private void AddToSecond(object text1, object text2)
{
DataRow dr24 = second.NewRow();
dr24[0] = text1;
dr24[1] = text2;
second.Rows.Add(dr24);
}
}
}