Поделиться через


Queryable.LongCount Метод

Определение

Возвращает значение Int64 , представляющее количество элементов в последовательности.

Перегрузки

Имя Описание
LongCount<TSource>(IQueryable<TSource>)

Возвращает Int64, представляющую общее количество элементов в последовательности.

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

Возвращает значение Int64 , представляющее количество элементов в последовательности, удовлетворяющей условию.

LongCount<TSource>(IQueryable<TSource>)

Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs

Возвращает Int64, представляющую общее количество элементов в последовательности.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static long LongCount(System::Linq::IQueryable<TSource> ^ source);
public static long LongCount<TSource>(this System.Linq.IQueryable<TSource> source);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static long LongCount<TSource>(this System.Linq.IQueryable<TSource> source);
static member LongCount : System.Linq.IQueryable<'Source> -> int64
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member LongCount : System.Linq.IQueryable<'Source> -> int64
<Extension()>
Public Function LongCount(Of TSource) (source As IQueryable(Of TSource)) As Long

Параметры типа

TSource

Тип элементов source.

Параметры

source
IQueryable<TSource>

Объект IQueryable<T> , содержащий элементы для подсчета.

Возвращаемое значение

Число элементов в source.

Атрибуты

Исключения

source равно null.

Число элементов превышает Int64.MaxValue.

Примеры

В следующем примере кода показано, как использовать LongCount<TSource>(IQueryable<TSource>) для подсчета элементов в массиве.

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

long count = fruits.AsQueryable().LongCount();

Console.WriteLine("There are {0} fruits in the collection.", count);

/*
    This code produces the following output:

    There are 6 fruits in the collection.
*/
Dim fruits() As String = {"apple", "banana", "mango", _
                      "orange", "passionfruit", "grape"}

Dim count As Long = fruits.AsQueryable().LongCount()

MsgBox(String.Format("There are {0} fruits in the collection.", count))

' This code produces the following output:

' There are 6 fruits in the collection.

Комментарии

Метод LongCount<TSource>(IQueryable<TSource>) создает объект MethodCallExpression , представляющий LongCount<TSource>(IQueryable<TSource>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionExecute<TResult>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.

Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов LongCount<TSource>(IQueryable<TSource>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он подсчитывает количество элементов source и возвращает значение Int64.

Применяется к

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

Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs

Возвращает значение Int64 , представляющее количество элементов в последовательности, удовлетворяющей условию.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static long LongCount(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, bool> ^> ^ predicate);
public static long LongCount<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static long LongCount<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
static member LongCount : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> int64
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member LongCount : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> int64
<Extension()>
Public Function LongCount(Of TSource) (source As IQueryable(Of TSource), predicate As Expression(Of Func(Of TSource, Boolean))) As Long

Параметры типа

TSource

Тип элементов source.

Параметры

source
IQueryable<TSource>

Объект IQueryable<T> , содержащий элементы для подсчета.

predicate
Expression<Func<TSource,Boolean>>

Функция для проверки каждого элемента для условия.

Возвращаемое значение

Количество элементов, удовлетворяющих условию в source функции предиката.

Атрибуты

Исключения

source или predicate есть null.

Число соответствующих элементов превышает Int64.MaxValue.

Примеры

В следующем примере кода показано, как с помощью LongCount<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) подсчета элементов в массиве, удовлетворяющего условию.

class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static void LongCountEx2()
{
    Pet[] pets = { new Pet { Name="Barley", Age=8 },
                   new Pet { Name="Boots", Age=4 },
                   new Pet { Name="Whiskers", Age=1 } };

    const int Age = 3;

    // Count the number of Pet objects where Pet.Age is greater than 3.
    long count = pets.AsQueryable().LongCount(pet => pet.Age > Age);

    Console.WriteLine("There are {0} animals over age {1}.", count, Age);
}

/*
    This code produces the following output:

    There are 2 animals over age 3.
*/
Structure Pet
    Public Name As String
    Public Age As Integer
End Structure

Shared Sub LongCountEx2()
    Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8}, _
                       New Pet With {.Name = "Boots", .Age = 4}, _
                       New Pet With {.Name = "Whiskers", .Age = 1}}

    Const Age As Integer = 3

    ' Count the number of Pet objects where Pet.Age is greater than 3.
    Dim count As Long = pets.AsQueryable().LongCount(Function(Pet) Pet.Age > Age)

    MsgBox(String.Format("There are {0} animals over age {1}.", count, Age))
End Sub

' This code produces the following output:

' There are 2 animals over age 3.

Комментарии

Этот метод имеет по крайней мере один параметр типа, аргумент типа Expression<TDelegate> которого является одним из Func<T,TResult> типов. Для этих параметров можно передать лямбда-выражение и скомпилировать его в Expression<TDelegate>лямбда-выражение.

Метод LongCount<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) создает объект MethodCallExpression , представляющий LongCount<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionExecute<TResult>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.

Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов LongCount<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он подсчитывает количество элементов в source соответствии с условием, указанным predicate и возвращает значение Int64.

Применяется к