Why List(Of T) doesn't have Count()?

杀马特。学长 韩版系。学妹 提交于 2019-12-03 13:07:55

Call the method without the extension method syntax:

Public Class MyList
    Inherits List(Of MyObject)

    Public ReadOnly Property SelectedCount() As Integer
        Get
            Return Enumerable.Count(Me, Function(obj) obj.IsSelected)
        End Get
    End Property
End Class

Make sure you have added an import to System.Linq.

  1. You can cast Me to IEnumerable(Of MyObject):

    Return DirectCast(Me, IEnumerable(Of MyObject)).Count(Function(obj) obj.IsSelected)
    

    Or use Enumerable.Count() method directly:

    Return Enumerable.Count(Me, Function(obj) obj.IsSelected)
    

    Extension Methods are transformed by compiler into direct static (shared in VB) methods calls, so there is no difference.

  2. Have no idea, really.

  3. Casting to underlying type does not change the object itself, so there is no performance penalty (unless boxing is involved, what is not a case here).

  4. C# does not allow properties with parameters and it requires properties to be called without (), so yes, it's better in situations like this one.

    In VB.NET both Me.Count() and Me.Count refer to Count property of List(Of T). In C# this.Count would refer to property and this.Count() would refer the extension method (because of parentheses).

Use AsEnumerable for this purpose:

Public ReadOnly Property SelectedCount() As Integer
    Get
        Return Me.AsEnumerable.Count(Function(obj) obj.IsSelected)
    End Get
End Property

To answer #4, this works fine in C#:

public class MyObject { public bool IsSelected { get { return true; } } }

public class MyList : List<MyObject>
{
    public int SelectedCount
    {
        get { return this.Count(x => x.IsSelected); }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!