2016-02-26 81 views
1

例如有两个表具有相同的架构,但不同的内容:什么是比较两个表的最快方法?

表1

| field1 | field2  | field3  | 
---------------------------------------- 
| 1  | aaaaa  | 100   | 
| 2  | bbbbb  | 200   | 
| 3  | ccccc  | 300   | 
| 4  | ddddd  | 400   | 

表2

| field1 | field2  | field3  | 
---------------------------------------- 
| 2  | xxxxx  | 200   | 
| 3  | ccccc  | 999   | 
| 4  | ddddd  | 400   | 
| 5  | eeeee  | 500   | 

预期比较结果将是:

删除了B:

| 1  | aaaaa  | 100   | 

不匹配:

Table1:| 2  | bbbbb  | 200   | 
Table2:| 2  | xxxxx  | 200   | 
Table1:| 3  | ccccc  | 300   | 
Table2:| 3  | ccccc  | 999   | 

B中

| 5  | eeeee  | 500   | 

新增使用C#,什么是最快的方法比较两张桌子?

当前我的实现是: 检查table1中的每一行在table2中是否有完全匹配; 检查table2中的每一行是否在table1中有完全匹配。

效率是n*n所以对于10万行,需要20分钟才能在服务器上运行。

非常感谢

+0

他们是'DataTables'吗?如果是这样的话,定义(主键)并进行比较。 –

回答

2

你可以尝试这样的事情,应该是相当快:

class objType 
{ 
    public int Field1 { get; set; } 
    public string Field2 { get; set; } 
    public int Field3 { get; set; } 

    public bool AreEqual(object other) 
    { 
     var otherType = other as objType; 
     if (otherType == null) 
      return false; 
     return Field1 == otherType.Field1 && Field2 == otherType.Field2 && Field3 == otherType.Field3; 
    } 
} 

var tableOne = new objType[] { 
    new objType { Field1 = 1, Field2 = "aaaa", Field3 = 100 }, 
    new objType { Field1 = 2, Field2 = "bbbb", Field3 = 200 }, 
    new objType { Field1 = 3, Field2 = "cccc", Field3 = 300 }, 
    new objType { Field1 = 4, Field2 = "dddd", Field3 = 400 } 
}; 

var tableTwo = new objType[] { 
    new objType { Field1 = 2, Field2 = "xxxx", Field3 = 200 }, 
    new objType { Field1 = 3, Field2 = "cccc", Field3 = 999 }, 
    new objType { Field1 = 4, Field2 = "dddd", Field3 = 400 }, 
    new objType { Field1 = 5, Field2 = "eeee", Field3 = 500 } 
}; 

var originalIds = tableOne.ToDictionary(o => o.Field1, o => o); 
var newIds = tableTwo.ToDictionary(o => o.Field1, o => o); 

var deleted = new List<objType>(); 
var modified = new List<objType>(); 

foreach (var row in tableOne) 
{ 
    if(!newIds.ContainsKey(row.Field1)) 
     deleted.Add(row); 
    else 
    { 
     var otherRow = newIds[row.Field1]; 
     if (!otherRow.AreEqual(row)) 
     { 
      modified.Add(row); 
      modified.Add(otherRow); 
     } 
    } 
} 

var added = tableTwo.Where(t => !originalIds.ContainsKey(t.Field1)).ToList(); 

可能是值得重写Equals代替AreEqual(或使AreEqual类定义之外的helper方法)但这取决于你的项目是如何设置的。

+0

谢谢。它运作良好! – BayOtter

相关问题