Udostępnij za pośrednictwem


Observable.Aggregate<TSource, TAccumulate> , metoda (IObservable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>)

Stosuje funkcję akumulatorów do obserwowanej sekwencji z określoną wartością inicju.

Przestrzeń nazw:System.Reactive.Linq
Zestawu: System.Reactive (w System.Reactive.dll)

Składnia

'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.

Parametry typu

  • Tsource
    Typ źródła.
  • Taccumulate
    Typ gromadzenia.

Parametry

  • Nasion
    Typ: TAccumulate
    Początkowa wartość akumulatorowa.
  • Akumulator
    Typ: System.Func<TAccumulate, TSource, TAccumulate>
    Funkcja akumulatorowa, która ma być wywoływana na każdym elemecie.

Wartość zwracana

Typ: System.IObservable<TAccumulate>
Obserwowana sekwencja zawierająca pojedynczy element z końcową wartością akumulatorową.

Uwaga dotycząca użycia

W języku Visual Basic i C# można wywołać tę metodę jako metodę wystąpienia dla dowolnego obiektu typu IObservable<TSource>. Gdy w celu wywołania tej metody jest używana składnia metody wystąpienia, należy pominąć pierwszy parametr. Aby uzyskać więcej informacji, zobacz lub .

Uwagi

Operator agregacji służy do stosowania funkcji w sekwencji źródłowej w celu wygenerowania wartości zagregowanej lub skumulowanej. Funkcja stosowana w sekwencji jest nazywana funkcją akumulatorową. Wymaga dwóch parametrów: wartości akumulatorowej i elementu z sekwencji, która jest przetwarzana z wartością akumulatorową. Początkowa wartość akumulatorowa jest nazywana wartością inicjatora i musi zostać podana operatorowi agregacji. Funkcja akumulatorowa zwraca nową wartość akumulatorów za każdym razem, gdy jest wywoływana. Nowa wartość akumulatorowa jest następnie używana z następnym wywołaniem funkcji akumulatorowej w celu przetworzenia elementu w sekwencji. Te wywołania są kontynuowane do końca sekwencji.

Operator agregacji zwraca obserwowaną sekwencję, która jest tego samego typu co wartość inicjatora przekazywana do operatora. Aby uzyskać ostateczną wartość agregacji, subskrybujesz obserwowaną sekwencję zwróconą z operatora agregacji. Po zastosowaniu funkcji akumulatorowej w całej sekwencji programy obsługi OnNext i OnCompleted obserwatora podane w subskrypcji są wywoływane w celu zapewnienia ostatecznej wartości zagregowanej. Zobacz przykładowy kod dostarczony z tym operatorem.

Przykłady

W tym przykładzie pokazano użycie operatora agregacji do zliczenia wirtualnych w ciągu znaków generowanych w czasie wykonywania za pomocą elementu Console.Readkey(). Funkcja CountVowels jest funkcją akumulatorów i zwiększa liczbę każdej vowel napotkanej w sekwencji.

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;
    }
  }
}

Oto przykładowe dane wyjściowe z przykładowego kodu.

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...

Zobacz też

Odwołanie

Obserwowalne, klasa

Przeciążenie agregacji

Przestrzeń nazw System.Reactive.Linq