SortedDictionary的except函数的奇怪行为

时间:2013-02-13 15:23:28

标签: c#

我正在尝试使用SortedDicationary的Except-Function,但我却疯了,因为它没有像我预期的那样表现。只要字典的条目是简单数据类型,Excpet函数就会起作用。但是,我想在dictionay中存储对象。

这是我的样本:

 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'。

据我所知,匹配仅基于每个条目的密钥进行。所以我认为没有理由使用自定义的比较类。

有关于此的任何想法吗?

2 个答案:

答案 0 :(得分:1)

Except不是SortedDictionary<TKey, TValue>上的方法 这是IEnumerable<T>的扩展方法 对于排序字典,T实际上是KeyValuePair<TKey, TValue>

因此,Except会比较KeyValuePair<TKey, TValue>的实例 如果KeyValuePair<TKey, TValue>Key相同,则Value的两个实例被视为相同。
因为您每次都创建一个新的object实例,所以KeyValuePair<TKey, TValue>的所有三个实例都被视为彼此不相等。
您可以通过将代码更改为以下内容来轻松验证:

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

objects.Except(objects2)的结果现在只是包含密钥"B"的条目。

答案 1 :(得分:0)

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

IEnumerable<KeyValuePair<string, Object>> objects_a_only = objects
        .Where(kvp => !objects2.ContainsKey(kvp.Key));