Queryable.Count Method

Definition

Retorna o número de elementos em uma sequência.Returns the number of elements in a sequence.

Overloads

Count<TSource>(IQueryable<TSource>)

Retorna o número de elementos em uma sequência.Returns the number of elements in a sequence.

Count<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)

Retorna o número de elementos na sequência especificada que atendem a uma condição.Returns the number of elements in the specified sequence that satisfies a condition.

Count<TSource>(IQueryable<TSource>)

Retorna o número de elementos em uma sequência.Returns the number of elements in a sequence.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static int Count(System::Linq::IQueryable<TSource> ^ source);
public static int Count<TSource> (this System.Linq.IQueryable<TSource> source);
static member Count : System.Linq.IQueryable<'Source> -> int
<Extension()>
Public Function Count(Of TSource) (source As IQueryable(Of TSource)) As Integer

Type Parameters

TSource

O tipo dos elementos de source.The type of the elements of source.

Parameters

source
IQueryable<TSource>

O IQueryable<T> que contém os elementos a serem contados.The IQueryable<T> that contains the elements to be counted.

Returns

Int32

O número de elementos na sequência de entrada.The number of elements in the input sequence.

Exceptions

source é null.source is null.

O número de elementos no source é maior que MaxValue.The number of elements in source is larger than MaxValue.

Examples

O exemplo de código a seguir demonstra como usar Count<TSource>(IQueryable<TSource>) para contar os elementos em uma sequência.The following code example demonstrates how to use Count<TSource>(IQueryable<TSource>) to count the elements in a sequence.

string[] fruits = { "apple", "banana", "mango",
                    "orange", "passionfruit", "grape" };

int numberOfFruits = fruits.AsQueryable().Count();

Console.WriteLine(
    "There are {0} items in the array.",
    numberOfFruits);

// This code produces the following output:
//
// There are 6 items in the array.

Dim fruits() As String = {"apple", "banana", "mango", _
                    "orange", "passionfruit", "grape"}

Dim numberOfFruits As Integer = fruits.AsQueryable().Count()

MsgBox(String.Format( _
    "There are {0} items in the array.", _
    numberOfFruits))

' This code produces the following output:
'
' There are 6 items in the array. 

Remarks

O método Count<TSource>(IQueryable<TSource>) gera um MethodCallExpression que representa a chamada Count<TSource>(IQueryable<TSource>) si mesmo como um método genérico construído.The Count<TSource>(IQueryable<TSource>) method generates a MethodCallExpression that represents calling Count<TSource>(IQueryable<TSource>) itself as a constructed generic method. Em seguida, ele passa o MethodCallExpression para o método Execute<TResult>(Expression) do IQueryProvider representado pela propriedade Provider do parâmetro source.It then passes the MethodCallExpression to the Execute<TResult>(Expression) method of the IQueryProvider represented by the Provider property of the source parameter.

O comportamento da consulta que ocorre como resultado da execução de uma árvore de expressão que representa a chamada de Count<TSource>(IQueryable<TSource>) depende da implementação do tipo do parâmetro source.The query behavior that occurs as a result of executing an expression tree that represents calling Count<TSource>(IQueryable<TSource>) depends on the implementation of the type of the source parameter. O comportamento esperado é que ele conta o número de itens em source.The expected behavior is that it counts the number of items in source.

Count<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)

Retorna o número de elementos na sequência especificada que atendem a uma condição.Returns the number of elements in the specified sequence that satisfies a condition.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static int Count(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, bool> ^> ^ predicate);
public static int Count<TSource> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
static member Count : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> int
<Extension()>
Public Function Count(Of TSource) (source As IQueryable(Of TSource), predicate As Expression(Of Func(Of TSource, Boolean))) As Integer

Type Parameters

TSource

O tipo dos elementos de source.The type of the elements of source.

Parameters

source
IQueryable<TSource>

Um IQueryable<T> que contém os elementos a serem contados.An IQueryable<T> that contains the elements to be counted.

predicate
Expression<Func<TSource,Boolean>>

Uma função para testar cada elemento em relação a uma condição.A function to test each element for a condition.

Returns

Int32

O número de elementos na sequência que atende à condição na função de predicado.The number of elements in the sequence that satisfies the condition in the predicate function.

Exceptions

source ou predicate é null.source or predicate is null.

O número de elementos no source é maior que MaxValue.The number of elements in source is larger than MaxValue.

Examples

O exemplo de código a seguir demonstra como usar Count<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) para contar os elementos em uma sequência que atendem a uma condição.The following code example demonstrates how to use Count<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) to count the elements in a sequence that satisfy a condition.

class Pet
{
    public string Name { get; set; }
    public bool Vaccinated { get; set; }
}

public static void CountEx2()
{
    // Create an array of Pet objects.
    Pet[] pets = { new Pet { Name="Barley", Vaccinated=true },
                   new Pet { Name="Boots", Vaccinated=false },
                   new Pet { Name="Whiskers", Vaccinated=false } };

    // Count the number of unvaccinated pets in the array.
    int numberUnvaccinated =
        pets.AsQueryable().Count(p => p.Vaccinated == false);

    Console.WriteLine(
        "There are {0} unvaccinated animals.",
        numberUnvaccinated);
}

// This code produces the following output:
//
// There are 2 unvaccinated animals.

Structure Pet
    Public Name As String
    Public Vaccinated As Boolean
End Structure

Shared Sub CountEx2()
    ' Create an array of Pet objects.
    Dim pets() As Pet = {New Pet With {.Name = "Barley", .Vaccinated = True}, _
                   New Pet With {.Name = "Boots", .Vaccinated = False}, _
                   New Pet With {.Name = "Whiskers", .Vaccinated = False}}

    ' Count the number of unvaccinated pets in the array.
    Dim numberUnvaccinated As Integer = pets.AsQueryable().Count(Function(p) p.Vaccinated = False)

    MsgBox(String.Format("There are {0} unvaccinated animals.", numberUnvaccinated))
End Sub

' This code produces the following output:
'
' There are 2 unvaccinated animals.

Remarks

Esse método tem pelo menos um parâmetro do tipo Expression<TDelegate> cujo argumento de tipo é um dos tipos de Func<T,TResult>.This method has at least one parameter of type Expression<TDelegate> whose type argument is one of the Func<T,TResult> types. Para esses parâmetros, você pode passar uma expressão lambda e ela será compilada para um Expression<TDelegate>.For these parameters, you can pass in a lambda expression and it will be compiled to an Expression<TDelegate>.

O método Count<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) gera um MethodCallExpression que representa a chamada Count<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) si mesmo como um método genérico construído.The Count<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) method generates a MethodCallExpression that represents calling Count<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) itself as a constructed generic method. Em seguida, ele passa o MethodCallExpression para o método Execute<TResult>(Expression) do IQueryProvider representado pela propriedade Provider do parâmetro source.It then passes the MethodCallExpression to the Execute<TResult>(Expression) method of the IQueryProvider represented by the Provider property of the source parameter.

O comportamento da consulta que ocorre como resultado da execução de uma árvore de expressão que representa a chamada de Count<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) depende da implementação do tipo do parâmetro source.The query behavior that occurs as a result of executing an expression tree that represents calling Count<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) depends on the implementation of the type of the source parameter. O comportamento esperado é que ele conta o número de itens em source que atendem à condição especificada por predicate.The expected behavior is that it counts the number of items in source that satisfy the condition specified by predicate.

Applies to