代码之家  ›  专栏  ›  技术社区  ›  Thorin Oakenshield

在C语言中使用LINQ比较字典#

  •  2
  • Thorin Oakenshield  · 技术社区  · 14 年前

    这两本字典像

    Dictionary<String, List<String>> DICTONE = new Dictionary<string, List<String>>();
    Dictionary<string, List<String>> DICTTWO = new Dictionary<string, List<String>>();
    

    内容呢

    DICTONE["KEY1"]="A"
                    "B"
                    "C"
    
    DICTONE["KEY2"]="D"
                    "E"
                    "F"
    
    DICTTWO["KEY1"]="A"
                    "B"
                    "Z"
    
    DICTTWO["KEY3"]="W"
                    "X"
                    "Y"
    

    第三个字典有一个类实例作为值

    Dictionary<String, MyClass> DICTRESULT = new Dictionary<string, MyClass>();
    

    这个班就像

    class MyClass
    {
        public List<string> Additional = null;
            public List<string> Missing = null; 
    
        public MyClass()
            {
                Additional = new List<string>();
                Missing = new List<string>();
            }
            public MyClass(List<string> p_Additional, List<string> p_Missing)
            {
                Additional = p_Additional;
                Missing = p_Missing;
            }
    }
    

    1. 如果一个项目在DICTTWO中而不是在DICTTONE中,则将该项目添加到RESULTDICT的附加列表中

    预期的答案是

    DICTRESULT["KEY1"]=ADDITIONAL LIST ---> "Z"
                       MISSING LIST    ---> "C"
    
    DICTRESULT["KEY2"]=ADDITIONAL LIST ---> ""
                       MISSING LIST    ---> "D"
                                            "E"
                                            "F"
    DICTRESULT["KEY3"]=ADDITIONAL LIST ---> ""
                       MISSING LIST    ---> "W"
                                            "X"
                                            "Y"
    

    使用LINQ有什么方法可以做到这一点吗

    1 回复  |  直到 14 年前
        1
  •  2
  •   Jon Skeet    14 年前

    好吧,这是一个尝试,假设 first second 是有问题的词典。

    var items = from key in first.Keys.Concat(second.Keys).Distinct()
                let firstList = first.GetValueOrDefault(key) ?? new List<string>()
                let secondList = second.GetValueOrDefault(key) ?? new List<string>()
                select new { Key = key,
                             Additional = secondList.Except(firstList),
                             Missing = firstList.Except(secondList) };
    var result = items.ToDictionary(x => x.Key,
                                    x => new MyClass(x.Additional, x.Missing));
    

    public static TValue GetValueOrDefault<TKey, TValue>
        (this IDictionary<TKey, TValue> dictionary,
         TKey key)
    {
        TValue value;
        dictionary.TryGetValue(key, out value)
        return value;
    }