Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
Aplica una función de acumulador sobre una secuencia observable con el valor de inicialización especificado.
Espacio de nombres:System.Reactive.Linq
Ensamblaje: System.Reactive (en System.Reactive.dll)
Sintaxis
'Declaration
<ExtensionAttribute> _
Public Shared Function Aggregate(Of TSource, TAccumulate) ( _
source As IObservable(Of TSource), _
seed As TAccumulate, _
accumulator As Func(Of TAccumulate, TSource, TAccumulate) _
) As IObservable(Of TAccumulate)
'Usage
Dim source As IObservable(Of TSource)
Dim seed As TAccumulate
Dim accumulator As Func(Of TAccumulate, TSource, TAccumulate)
Dim returnValue As IObservable(Of TAccumulate)
returnValue = source.Aggregate(seed, _
accumulator)
public static IObservable<TAccumulate> Aggregate<TSource, TAccumulate>(
this IObservable<TSource> source,
TAccumulate seed,
Func<TAccumulate, TSource, TAccumulate> accumulator
)
[ExtensionAttribute]
public:
generic<typename TSource, typename TAccumulate>
static IObservable<TAccumulate>^ Aggregate(
IObservable<TSource>^ source,
TAccumulate seed,
Func<TAccumulate, TSource, TAccumulate>^ accumulator
)
static member Aggregate :
source:IObservable<'TSource> *
seed:'TAccumulate *
accumulator:Func<'TAccumulate, 'TSource, 'TAccumulate> -> IObservable<'TAccumulate>
JScript does not support generic types and methods.
Parámetros de tipo
- TSource
Tipo de origen.
- TAccumulate
Tipo de acumulado.
Parámetros
- source
Tipo: System.IObservable<TSource>
Secuencia observable que se va a agregar.
- seed
Tipo: TAccumulate
Valor de inicio del acumulador.
- Acumulador
Tipo: System.Func<TAccumulate, TSource, TAccumulate>
Función de acumulador que se va a invocar en cada elemento.
Valor devuelto
Tipo: System.IObservable<TAccumulate>
Secuencia observable que contiene un único elemento con el valor final del acumulador.
Nota sobre el uso
En Visual Basic y C#, puede llamar a este método como un método de instancia en cualquier objeto de tipo IObservable<TSource>. Cuando emplee la sintaxis del método de instancia para llamar a este método, omita el primer parámetro. Para obtener más información, vea o .
Observaciones
El operador de agregado se usa para aplicar una función en una secuencia de origen para generar un valor agregado o acumulado. La función aplicada a través de la secuencia se denomina función de acumulador. Requiere dos parámetros: un valor de acumulador y un elemento de la secuencia que se procesa con el valor del acumulador. El valor inicial del acumulador se denomina valor de inicialización y se debe proporcionar al operador de agregado. La función de acumulador devuelve el nuevo valor de acumulador cada vez que se llama a él. A continuación, se usa el nuevo valor del acumulador con la siguiente llamada a la función de acumulador para procesar el elemento en la secuencia. Estas llamadas continúan hasta el final de la secuencia.
El operador de agregado devuelve una secuencia observable que es del mismo tipo que el valor de inicialización que se pasa al operador . Para obtener el valor agregado final, suscríbase a la secuencia observable devuelta por el operador de agregado. Una vez que se ha aplicado la función de acumulador en toda la secuencia, se llama a los controladores OnNext y OnCompleted del observador proporcionados en la suscripción para proporcionar el valor agregado final. Consulte el código de ejemplo proporcionado con este operador.
Ejemplos
En este ejemplo se muestra el uso del operador de agregado para contar las vocales en una cadena de caracteres generados en tiempo de ejecución con Console.Readkey(). La función CountVowels es la función de acumulador e incrementa el recuento de cada vocal encontrado en la secuencia.
using System;
using System.Reactive.Linq;
namespace Example
{
class Program
{
enum Vowels : int
{
A, E, I, O, U
};
static void Main()
{
//****************************************************************************************//
//*** Create an observable sequence of char from console input until enter is pressed. ***//
//****************************************************************************************//
IObservable<char> xs = Observable.Create<char>(observer =>
{
bool bContinue = true;
while (bContinue)
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (keyInfo.Key != ConsoleKey.Enter)
{
Console.Write(keyInfo.KeyChar);
observer.OnNext(keyInfo.KeyChar);
}
else
{
observer.OnCompleted();
Console.WriteLine("\n");
bContinue = false;
}
}
return (() => { });
});
//***************************************************************************************//
//*** ***//
//*** The "Aggregate" operator causes the accumulator function, "CountVowels", to be ***//
//*** called for each character in the sequence. ***//
//*** ***//
//*** The seed value is the integer array which will hold a count of each of the five ***//
//*** vowels encountered. It is passed as a parameter to Aggregate. ***//
//*** The seed value will be passed to CountVowels and processed with the first item ***//
//*** in the sequence. ***//
//*** ***//
//*** The return value from "CountVowels" is the same type as the seed parameter. ***//
//*** That return value is subsequently passed into each call to the accumulator with ***//
//*** its corresponding character from the sequence. ***//
// ***//
//*** The event handler, "OnNext", is not called until the accumulator function has ***//
//*** been executed across the entire sequence. ***//
//*** ***//
//***************************************************************************************//
Console.WriteLine("\nEnter a sequence of characters followed by the ENTER key.\n" +
"The example code will count the vowels you enter\n");
using (IDisposable handle = xs.Aggregate(new int[5], CountVowels).Subscribe(OnNext))
{
Console.WriteLine("\nPress ENTER to exit...");
Console.ReadLine();
}
}
//*********************************************************************************************************//
//*** ***//
//*** The Event handler, "OnNext" is called when the event stream that Aggregate is processing ***//
//** completes. ***//
//*** ***//
//*** The final accumulator value is passed to the handler. In this example, it is the array containing ***//
//*** final count of each vowel encountered. ***//
//*** ***//
//*********************************************************************************************************//
static void OnNext(int[] state)
{
Console.WriteLine("Vowel Final Count = A:{0}, E:{1}, I:{2}, O:{3}, U:{4}\n",
state[(int)Vowels.A],
state[(int)Vowels.E],
state[(int)Vowels.I],
state[(int)Vowels.O],
state[(int)Vowels.U]);
}
//*********************************************************************************************************//
//*** ***//
//*** CountVowels will be called for each character event in the event stream. ***//
//*** ***//
//*** The int array, "state", is used as the accumulator. It holds a count for each vowel. ***//
//*** ***//
//*** CountVowels simply looks at the character "ch" to see if it is a vowel and increments that vowel ***//
//*** count in the array. ***//
//*** ***//
//*********************************************************************************************************//
static int[] CountVowels(int[] state, char ch)
{
char lch = char.ToLower(ch);
switch (lch)
{
case 'a': state[(int)Vowels.A]++;
break;
case 'e': state[(int)Vowels.E]++;
break;
case 'i': state[(int)Vowels.I]++;
break;
case 'o': state[(int)Vowels.O]++;
break;
case 'u': state[(int)Vowels.U]++;
break;
};
return state;
}
}
}
Este es el resultado de ejemplo del código de ejemplo.
Enter a sequence of characters followed by the ENTER key.
The example code will count the vowels you enter
This is a sequence of char I am generating from Console.ReadKey()
Vowel Final Count = A:5, E:8, I:4, O:4, U:1
Press ENTER to exit...