2015-01-13 85 views
2

當我嘗試使用.Count之間的()在VB.NET以下無法從LINQ的字典

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小提琴失敗 - 奇......這是怎麼回事?):

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

什麼是正確的方法對字典使用LINQ版本.Count()with a predicate

+0

相關:http://stackoverflow.com/q/18743457/945456 –

回答

7

當名稱發生衝突時,您需要使用AsEnumerable()(請參閱備註部分)來獲取擴展方法。

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

然而,有一個原因是在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.

一個Dictionary(Of TKey, TValue) Class已經有一個屬性名爲Count所以Count擴展隱。

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

我會跳過如何,部分是因爲@馬克已經answerd說。

+1

感謝您的解釋。希望我有一個'部分答案'我可以獎給你們兩個;) –