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

若如初见. 提交于 2021-01-27 16:39:36

问题


When I try the following in VB.NET

Dim data = New Dictionary(Of String, Integer)
data.Count(Function(x) x.Value > 0) 'Compile-time error!

I get this compile error with .Net Fiddle:

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

Visual Studio gives me this error:

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

The following does work though:

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

It seems to not be finding the correct overload.

Oddly, enough the C# version of this works just fine in Visual Studio (but fails in .NET Fiddle - odd... what's going on?):

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

What's the correct way to use the LINQ version of .Count() with a predicate against a dictionary?


回答1:


You need to use AsEnumerable() (see the Remarks section) to pick up the extension methods when the names clash.

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



回答2:


There is however a reason why in VB.NET it works differently from 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.

and even

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 so the Count extension is hidden.

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

I'll skip the how-part because @Mark's already answerd that.



来源:https://stackoverflow.com/questions/27932993/cant-use-count-from-linq-on-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!