detect changed items between 2 dictionary

detect changed items between 2 dictionary

private static void DiffDictionaries<T, U>(
    Dictionary<T, U> dicA,
    Dictionary<T, U> dicB,
    out Dictionary<T, U> dicAdd,
    out Dictionary<T, U> dicDel)
{
    // dicDel has entries that are in A, but not in B, 
    // ie they were deleted when moving from A to B
    int diff = Mathf.Abs(dicA.Count - dicB.Count);
    dicDel = new Dictionary<T, U>(diff);
    diffDicSub(dicA, dicB, dicDel);

    // dicAdd has entries that are in B, but not in A,
    // ie they were added when moving from A to B
    dicAdd = new Dictionary<T, U>(diff);
    diffDicSub(dicB, dicA, dicAdd);

    void diffDicSub(
    Dictionary<T, U> dicA,
    Dictionary<T, U> dicB,
    Dictionary<T, U> dicAExceptB)
    {
        // Walk A, and if any of the entries are not
        // in B, add them to the result dictionary.

        foreach (KeyValuePair<T, U> kvp in dicA)
        {
            //if (!dicB.Contains(kvp))
            if (!(dicB.TryGetValue(kvp.Key, out var val) && dicB[kvp.Key].Equals(kvp.Value)))
            {
                dicAExceptB[kvp.Key] = kvp.Value;
            }
        }
    }
}

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料