2013-07-16 114 views
2

我有两个字典:(LINQ)字典:除了不返回字典

Dim a As Dictionary(Of String, Type) 
Dim b As Dictionary(Of String, Type) 

我需要的是在a不在b应该是这样的:

a = a.Except(b) 

但它给我一个例外:

Unable to cast object of type 
    '<ExceptIterator>d__99`1[System.Collections.Generic.KeyValuePair`2[System.String,System.Type]]' 
to type 
    'System.Collections.Generic.Dictionary`2[System.String,System.Type]' 

如果我使用匿名变量它一切正常,但我需要它是强类型。

任何想法我做错了什么?

在此先感谢!

p.s .:对于这个例外,我猜它必须是与keyValuPair相关的东西,但我还没有找到解决的办法。

回答

4

你是对的Except返回IEnumerable(Of KeyValuePair(Of String, Type))。你可以解决这个问题通过调用ToDictionary扩展方法:

a = a.Except(b) _ 
    .ToDictionary(Function(x) x.Key, Function(x) x.Value) 

但是,这可能会更好,因为它不涉及创建一个新的字典:

For Each x in a.Intersect(b) 
    a.Remove(x.Key) 
Next 
+0

我试图说,但由于某些原因,当我'x.'这不是让我用'Key' – Luis

+0

@Luis这绝对* *应工作。我自己测试它只是为了确保。 –

+0

嗯,我关闭VS,重新打开它,重建并...它的工作...谢谢 – Luis

0

这应该修复它 - 添加一个ToList在你的表达式结尾。

A = a.Except(B).ToList