Jeff B
Jeff B

Reputation: 8982

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

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?

Upvotes: 3

Views: 992

Answers (2)

t3chb0t
t3chb0t

Reputation: 18675

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.

Upvotes: 3

Mark
Mark

Reputation: 8160

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)

Upvotes: 7

Related Questions