c# - 比较两个词典,了解每个“添加”操作和每个“删除”操作

时间:2011-09-13 21:04:07

标签: c# .net .net-3.5 dictionary change-tracking

我有2个带有similaire struture的词典

Dictionary<string, List<int>> Origins

Dictionary<string, List<int>> Changes

我一开始就创造了起源。这是开始状态的副本。 示例:

Origins["toto"] = new List<int>(){1,2,3};
Origins["tata"] = new List<int>();
Origins["titi"] = new List<int>(){1,2};

用户操作后,我会将更改保留在更改词典中。 基本上,用户可以添加或删除链接到字符串的一些数字。所以我保留了所有这些变化的痕迹:

示例:如果用户在“tata”中添加1 在字典中更改一个 “tata”有1个

如果用户在“toto”中添加4 在字典中更改一个  “toto”有1,2,3,4

如果用户在“titi”中删除1 在字典中更改一个 “蒂蒂”有2个

我需要使用Changes dictionnary来了解用户何时返回原始状态,并进行简单的比较。

如果没有对字符串进行任何更改,则更改字典没有此字符串的任何条目。

经过多次更改后,用户可以保存更改。 所以现在我需要找到所有添加和删除操作。

我的第一个想法是比较两个字典,看操作添加和操作删除。但是怎么样? 如果我比较相同字符串的列表,我可能知道差异,但我被困在这里。 也许有更好的方法来做到这一点?有什么建议吗?

4 个答案:

答案 0 :(得分:2)

您有以下情况:

  1. 新的字符串键添加到Changes,以及一些相关值。
  2. 更改现有字符串键的值(添加或删除值)。
  3. 如果(1)您在Changes中有一个Origins中不存在的条目。在情况(2)中,您将在两者中都有一个条目,但具有不同的值列表。

    (我将假设的值是一个数学集,即特定值只能出现在那里一次而且排序无关紧要。如果不是这种情况那么你将不得不稍微修改一下这个方法。)

    要检测案例(1),您可以找到唯一的键:

    IEnumerable<string> newKeys = Changes.Keys.Except(Origins.Keys);
    

    显然,Changes中新密钥的每个值都需要“添加”。您可以简单地迭代newKeys枚举,并从Changes

    中检索值
    foreach (string key in newKeys)
    {
        IEnumerable<int> addedValues = Changes[key];
        // your processing here
    }
    

    要检测案例(2),您需要迭代字典并比较Changes with Origins中的值集。为此,我们将迭代Origins以获取键值和原始值,然后使用Changes中的键检索项目。 (我们将这样做,因为如果我们迭代Changes,我们可能最终得到Origins中不存在的新增加的密钥,这是我们必须处理的另一种情况。)

    foreach (KeyValuePair<string, List<int>> entry in Origins)
    {
        List<int> originsValues = entry.Value;
        List<int> changesValues;
    
        // handle no key in Changes (as pointed out by Guillaume V). 
        if (!Changes.TryGet(entry.Key, out changesValues)) changesValues = originsValues;
    
        IEnumerable<int> removedValues = originsValues.Except(changesValues);
        IEnumerable<int> addedValues = changesValues.Except(originsValues);
    
        // your processing here
    }
    

答案 1 :(得分:1)

你可以试试这个:

        Dictionary<string, List<int>> Origin = new Dictionary<string, List<int>>();

        Origin["toto"] = new List<int>(){1,2,3};
        Origin["tata"] = new List<int>();
        Origin["titi"] = new List<int>(){1,2};


        Dictionary<string, List<int>> Changes = new Dictionary<string,List<int>>();

        Changes["toto"] = new List<int>() { 1, 2, 3, 4 };
        Changes["tata"] = new List<int>(){1};
        Changes["titi"] = new List<int>() { 2 };

        Dictionary<string, List<int>> ToRemove = new Dictionary<string, List<int>>();
        Dictionary<string, List<int>> ToAdd = new Dictionary<string, List<int>>();

        foreach (string key in Origin.Keys)
        {
            ToRemove[key] = Origin[key];
            ToAdd[key] = Changes[key];


            foreach (int i in ToRemove[key])
            {

                if (ToAdd[key].Contains(i)) //There is no change
                {
                    ToAdd[key].Remove(i);
                    ToRemove[key].Remove(i);
                }
            }
        }

答案 2 :(得分:0)

如果您需要做的就是确定两个对象是否相等,我建议您创建自己的类,并覆盖Equals()GetHashInfo()

public class ComparableDictionary : Dictionary<string, List<int>>
{
    private const int CouldBeAnyConstant = 392;

    public override bool Equals(object other)
    {
        return Equals((ComparableDictionary)other);
    }

    public bool Equals(ComparableDictionary other)
    {
        return other != null && (GetHashCode() == other.GetHashCode());
    }

    public override int GetHashCode()
    {
        int result = CouldBeAnyConstant;
        unchecked
        {
            foreach (var list in Values)
                foreach (var value in list)
                    result = result*value.GetHashCode();

            foreach (var value in Keys)
                result = result * value.GetHashCode();
        }

        return result;
    }

}

然后你要做的就是:

public bool UserHasMadeChanges(ComparableDictionary Origins, ComparableDictionary Changes)
{
    return !Origins.Equals(Changes)
}

答案 3 :(得分:0)

受Paul Ruane和matmot的启发,我开发了自己的方式:

foreach (var change in this.Changes)
        {
            List<int> origin = this.Origins[change.Key];

            List<int> newValue = change.Value;

            //find the basic add and remove
            IEnumerable<int> remove = origin.Except(newValue);
            IEnumerable<int> add = newValue.Except(origin);

            if (!add.Any() && remove.Any())
            {
              //remove all in the remove list 
                continue;

            }
            else if (add.Any() && !remove.Any())
            {
              //add all in the add list
                continue;
            }

            //if in the same change there are add and remove 
            IEnumerable<int> dif1 = add.Except(remove);
            IEnumerable<int> dif2 = remove.Except(add);

            if (dif1.Any())
            {
                //add all in the dif1 list 

            }
            if (dif2.Any())
            {
                //remove all in  dif2 list


            }
        }

您如何看待这个?