1

我正在尝试利用 SortedDicationary 的异常功能,但我快疯了,因为它的行为不像我预期的那样。只要字典的条目是简单数据类型,Excpet 函数就可以工作。但是,我想将对象存储在字典中。

这是我的示例:

 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;


namespace DictionaryTest
{
    class Program
    {
        static void Main(string[] args)
        {

            SortedDictionary<string, Object> objects = new SortedDictionary<string, Object>();
            SortedDictionary<string, Object> objects2 = new SortedDictionary<string, Object>();




            objects.Add("A", new Object());
            objects.Add("B", new Object());
            objects2.Add("A", new Object());

            IEnumerable<KeyValuePair<string, Object>> objects_a_only = objects.Except(objects2);

            foreach (KeyValuePair<string, Object> o in objects_a_only)
            {
                Console.WriteLine(o.Key);


            }
            Console.WriteLine("Program finished. Press any key to continue");
            Console.ReadKey();


        }
    }
}

我期望只得到'A'作为输出,但它实际上返回'A'和'B'。

据我了解,匹配仅根据每个条目的键进行。所以我看不出有任何理由使用定制的比较类。

对此有什么想法吗?

4

2 回答 2

1

Except不是上的方法SortedDictionary<TKey, TValue>
它是一种扩展方法IEnumerable<T>
在排序字典的情况下,T实际上是KeyValuePair<TKey, TValue>.

因此,Except比较KeyValuePair<TKey, TValue>. 如果 the和 the相同,则认为
of 的两个实例相同。因为您每次都 创建一个新实例,所以所有三个实例都被认为彼此不相等。 您可以通过将代码更改为此轻松验证这一点:KeyValuePair<TKey, TValue>KeyValue
objectKeyValuePair<TKey, TValue>

var o = new object();
objects.Add("A", o);
objects.Add("B", new Object());
objects2.Add("A", o);

的结果objects.Except(objects2)现在将只是带有 key 的条目"B"

于 2013-02-13T15:24:55.347 回答
0

当你使用Enumerable.Except它时,它使用默认的相等比较器,它对于KeyValuePair类型比较键和值。您可以改用这种方法:

IEnumerable<KeyValuePair<string, Object>> objects_a_only = objects
        .Where(kvp => !objects2.ContainsKey(kvp.Key));
于 2013-02-13T15:29:54.637 回答