无法在字典上使用 LINQ 中的 .Count()

Can't use .Count() from LINQ on Dictionary

当我在 VB.NET

中尝试以下操作时
Dim data = New Dictionary(Of String, Integer)
data.Count(Function(x) x.Value > 0) 'Compile-time error!

我用 .Net Fiddle 得到这个编译错误:

Too many arguments to 'Public Overloads ReadOnly Property Count As Integer'

Visual Studio 给我这个错误:

'Public ReadOnly Property Count As Integer' has no parameters and its return type cannot be indexed.

以下内容确实有效:

Enumerable.Where(data, Function(x) x.Value > 0).Count() 'Works!
data.Where(Function(x) x.Value > 0).Count() 'Works!

似乎没有找到正确的重载。

奇怪的是,这个的 C# 版本在 Visual Studio 中工作得很好(但在 .NET Fiddle 中失败了 - 奇怪......这是怎么回事?):

var data = new Dictionary<string, int>();
data.Count(x => x.Value > 0);

针对字典使用 .Count() with a predicate LINQ 版本的正确方法是什么?

您需要使用 AsEnumerable()(请参阅备注部分)在名称冲突时选择扩展方法。

data.AsEnumerable().Count(Function(x) x.Value > 0)

然而,在 VB.NET 中它的工作方式与 C# 不同是有原因的:

When an in-scope instance method has a signature that is compatible with the arguments of a calling statement, the instance method is chosen in preference to any extension method. The instance method has precedence even if the extension method is a better match.

甚至

The situation is simpler with properties: if an extension method has the same name as a property of the class it extends, the extension method is not visible and cannot be accessed.

a Dictionary(Of TKey, TValue) Class already has a property named Count 所以 Count 扩展被隐藏了。

Extension Methods (Visual Basic) > Extension Methods, Instance Methods, and Properties

我将跳过操作部分,因为@Mark 已经回答了。