簡體   English   中英

比較兩個表的最快方法是什么?

[英]What is the fastest way to compare two tables?

例如,有兩個表具有相同的架構,但是內容不同:

表格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中是否完全匹配; 檢查表2中的每一行在表1中是否完全匹配。

效率為n*n因此對於100k行,在服務器上運行需要20分鍾。

非常感謝

您可以嘗試這樣的操作,應該很快:

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成為類定義之外的幫助方法),但這取決於您的項目的設置方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM