【问题标题】:Can't use .Count() from LINQ on Dictionary不能在字典上使用 LINQ 中的 .Count()
【发布时间】:2015-01-13 22:52:52
【问题描述】:

当我在 VB.NET 中尝试以下操作时

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

.Net Fiddle 出现此编译错误:

“公共重载只读属性计数为整数”的参数过多

Visual Studio 给我这个错误:

'Public ReadOnly Property Count As Integer'没有参数,它的返回类型不能被索引。

以下确实有效:

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 版本的正确方法是什么?

【问题讨论】:

标签: vb.net linq dictionary overloading


【解决方案1】:

当名称冲突时,您需要使用AsEnumerable()(参见备注部分)来选择扩展方法。

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

【讨论】:

    【解决方案2】:

    然而,VB.NETC# 的工作方式不同是有原因的:

    当范围内的实例方法具有与调用语句的参数兼容的签名时,会优先选择实例方法而不是任何扩展方法。 即使扩展方法更好匹配,实例方法也具有优先权。

    甚至

    使用属性的情况更简单:如果扩展方法与其扩展的类的属性同名,则扩展方法不可见且无法访问

    Dictionary(Of TKey, TValue) Class 已经有一个名为 Count 的属性,因此隐藏了 Count 扩展。

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

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

    【讨论】:

    • 感谢您的解释。希望我有一个Partial Class Answer 我可以奖励你们俩;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多