Enumerable.TakeWhile Método
Definición
Devuelve los elementos de una secuencia siempre que el valor de una condición especificada sea true y luego omite los elementos restantes.Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements.
Sobrecargas
TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) |
Devuelve los elementos de una secuencia en tanto que el valor de una condición especificada sea true.Returns elements from a sequence as long as a specified condition is true. |
TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>) |
Devuelve los elementos de una secuencia en tanto que el valor de una condición especificada sea true.Returns elements from a sequence as long as a specified condition is true. El índice del elemento se usa en la lógica de la función de predicado.The element's index is used in the logic of the predicate function. |
TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)
Devuelve los elementos de una secuencia en tanto que el valor de una condición especificada sea true.Returns elements from a sequence as long as a specified condition is true.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static System::Collections::Generic::IEnumerable<TSource> ^ TakeWhile(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, bool> ^ predicate);
public static System.Collections.Generic.IEnumerable<TSource> TakeWhile<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate);
static member TakeWhile : seq<'Source> * Func<'Source, bool> -> seq<'Source>
<Extension()>
Public Function TakeWhile(Of TSource) (source As IEnumerable(Of TSource), predicate As Func(Of TSource, Boolean)) As IEnumerable(Of TSource)
Parámetros de tipo
- TSource
Tipo de los elementos de source
.The type of the elements of source
.
Parámetros
- source
- IEnumerable<TSource>
Secuencia cuyos elementos se van a devolver.A sequence to return elements from.
Función para probar cada elemento de una condición.A function to test each element for a condition.
Devoluciones
- IEnumerable<TSource>
IEnumerable<T> que contiene los elementos de la secuencia de entrada que se encuentran antes del elemento que no supera la prueba.An IEnumerable<T> that contains the elements from the input sequence that occur before the element at which the test no longer passes.
Excepciones
source
o predicate
es null
.source
or predicate
is null
.
Ejemplos
En el ejemplo de código siguiente se muestra cómo usar TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) para devolver elementos desde el inicio de una secuencia siempre que se cumpla una condición.The following code example demonstrates how to use TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) to return elements from the start of a sequence as long as a condition is true.
string[] fruits = { "apple", "banana", "mango", "orange",
"passionfruit", "grape" };
IEnumerable<string> query =
fruits.TakeWhile(fruit => String.Compare("orange", fruit, true) != 0);
foreach (string fruit in query)
{
Console.WriteLine(fruit);
}
/*
This code produces the following output:
apple
banana
mango
*/
' Create an array of strings.
Dim fruits() As String =
{"apple", "banana", "mango", "orange", "passionfruit", "grape"}
' Take strings from the array until one of
' the strings matches "orange".
Dim query As IEnumerable(Of String) =
fruits.TakeWhile(Function(fruit) _
String.Compare("orange", fruit, True) <> 0)
' Display the results.
Dim output As New System.Text.StringBuilder
For Each fruit As String In query
output.AppendLine(fruit)
Next
Console.WriteLine(output.ToString())
' This code produces the following output:
'
' apple
' banana
' mango
Comentarios
Este método se implementa mediante la ejecución aplazada.This method is implemented by using deferred execution. El valor devuelto inmediato es un objeto que almacena toda la información necesaria para realizar la acción.The immediate return value is an object that stores all the information that is required to perform the action. La consulta representada por este método no se ejecuta hasta que el objeto se enumera mediante una llamada a su GetEnumerator
método directamente o mediante foreach
en Visual C# o For Each
en Visual Basic.The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator
method directly or by using foreach
in Visual C# or For Each
in Visual Basic.
El TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) método prueba cada elemento de mediante source
predicate
y produce el elemento si el resultado es true
.The TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) method tests each element of source
by using predicate
and yields the element if the result is true
. La enumeración se detiene cuando la función de predicado devuelve false
para un elemento o cuando source
no contiene más elementos.Enumeration stops when the predicate function returns false
for an element or when source
contains no more elements.
Los TakeWhile SkipWhile métodos y son complementos funcionales.The TakeWhile and SkipWhile methods are functional complements. Dada una secuencia coll
y una función pura p
, la concatenación de los resultados de coll.TakeWhile(p)
y coll.SkipWhile(p)
produce la misma secuencia que coll
.Given a sequence coll
and a pure function p
, concatenating the results of coll.TakeWhile(p)
and coll.SkipWhile(p)
yields the same sequence as coll
.
En Visual Basic sintaxis de expresiones de consulta, una Take While
cláusula se convierte en una invocación de TakeWhile .In Visual Basic query expression syntax, a Take While
clause translates to an invocation of TakeWhile.
Consulte también
Se aplica a
TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>)
Devuelve los elementos de una secuencia en tanto que el valor de una condición especificada sea true.Returns elements from a sequence as long as a specified condition is true. El índice del elemento se usa en la lógica de la función de predicado.The element's index is used in the logic of the predicate function.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static System::Collections::Generic::IEnumerable<TSource> ^ TakeWhile(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, int, bool> ^ predicate);
public static System.Collections.Generic.IEnumerable<TSource> TakeWhile<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,int,bool> predicate);
static member TakeWhile : seq<'Source> * Func<'Source, int, bool> -> seq<'Source>
<Extension()>
Public Function TakeWhile(Of TSource) (source As IEnumerable(Of TSource), predicate As Func(Of TSource, Integer, Boolean)) As IEnumerable(Of TSource)
Parámetros de tipo
- TSource
Tipo de los elementos de source
.The type of the elements of source
.
Parámetros
- source
- IEnumerable<TSource>
Secuencia cuyos elementos se van a devolver.The sequence to return elements from.
Función que va a probar cada elemento de origen para determinar si satisface una condición; el segundo parámetro de la función representa el índice del elemento de origen.A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
Devoluciones
- IEnumerable<TSource>
IEnumerable<T> que contiene los elementos de la secuencia de entrada que se encuentran antes del elemento que no supera la prueba.An IEnumerable<T> that contains elements from the input sequence that occur before the element at which the test no longer passes.
Excepciones
source
o predicate
es null
.source
or predicate
is null
.
Ejemplos
En el ejemplo de código siguiente se muestra cómo usar TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>) para devolver elementos desde el inicio de una secuencia siempre que una condición que use el índice del elemento sea true.The following code example demonstrates how to use TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>) to return elements from the start of a sequence as long as a condition that uses the element's index is true.
string[] fruits = { "apple", "passionfruit", "banana", "mango",
"orange", "blueberry", "grape", "strawberry" };
IEnumerable<string> query =
fruits.TakeWhile((fruit, index) => fruit.Length >= index);
foreach (string fruit in query)
{
Console.WriteLine(fruit);
}
/*
This code produces the following output:
apple
passionfruit
banana
mango
orange
blueberry
*/
' Create an array of strings.
Dim fruits() As String =
{"apple", "passionfruit", "banana", "mango",
"orange", "blueberry", "grape", "strawberry"}
' Take strings from the array until one
' of the string's lengths is greater than or
' equal to the string item's index in the array.
Dim query As IEnumerable(Of String) =
fruits.TakeWhile(Function(fruit, index) _
fruit.Length >= index)
' Display the results.
Dim output As New System.Text.StringBuilder
For Each fruit As String In query
output.AppendLine(fruit)
Next
Console.WriteLine(output.ToString())
' This code produces the following output:
'
' apple
' passionfruit
' banana
' mango
' orange
' blueberry
Comentarios
Este método se implementa mediante la ejecución aplazada.This method is implemented by using deferred execution. El valor devuelto inmediato es un objeto que almacena toda la información necesaria para realizar la acción.The immediate return value is an object that stores all the information that is required to perform the action. La consulta representada por este método no se ejecuta hasta que el objeto se enumera mediante una llamada a su GetEnumerator
método directamente o mediante foreach
en Visual C# o For Each
en Visual Basic.The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator
method directly or by using foreach
in Visual C# or For Each
in Visual Basic.
El TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>) método prueba cada elemento de mediante source
predicate
y produce el elemento si el resultado es true
.The TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>) method tests each element of source
by using predicate
and yields the element if the result is true
. La enumeración se detiene cuando la función de predicado devuelve false
para un elemento o cuando source
no contiene más elementos.Enumeration stops when the predicate function returns false
for an element or when source
contains no more elements.
El primer argumento de predicate
representa el elemento que se va a probar.The first argument of predicate
represents the element to test. El segundo argumento representa el índice de base cero del elemento dentro de source
.The second argument represents the zero-based index of the element within source
.
Los TakeWhile SkipWhile métodos y son complementos funcionales.The TakeWhile and SkipWhile methods are functional complements. Dada una secuencia coll
y una función pura p
, la concatenación de los resultados de coll.TakeWhile(p)
y coll.SkipWhile(p)
produce la misma secuencia que coll
.Given a sequence coll
and a pure function p
, concatenating the results of coll.TakeWhile(p)
and coll.SkipWhile(p)
yields the same sequence as coll
.
En Visual Basic sintaxis de expresiones de consulta, una Take While
cláusula se convierte en una invocación de TakeWhile .In Visual Basic query expression syntax, a Take While
clause translates to an invocation of TakeWhile.