Sdílet prostřednictvím


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

Použije funkci akumulátoru na pozorovatelnou sekvenci se zadanou počáteční hodnotou.

Obor názvů:System.Reactive.Linq
Sestavení: System.Reactive (v System.Reactive.dll)

Syntax

'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 zdroje.
  • Taccumulate
    Typ kumulace.

Parametry

  • source
    Typ: System.IObservable<TSource>
    Pozorovatelná sekvence, která se má agregovat.
  • Osiva
    Typ: TAccumulate
    Počáteční hodnota akumulátoru.
  • Akumulátor
    Typ: System.Func<TAccumulate, TSource, TAccumulate>
    Akumulátorová funkce, která má být vyvolána u každého prvku.

Návratová hodnota

Typ: System.IObservable<TAccumulate>
Pozorovatelná sekvence obsahující jeden prvek s konečnou hodnotou akumulátoru.

Poznámka k využití

V jazyce Visual Basic a C# můžete tuto metodu volat jako metodu instance u libovolného objektu typu IObservable<TSource>. Pokud k volání této metody použijete syntaxi metody instance, vynechejte první parametr. Další informace naleznete v tématech a .

Poznámky

Operátor agregace se používá k použití funkce ve zdrojové sekvenci k vytvoření agregované nebo kumulované hodnoty. Funkce použitá v celé sekvenci se nazývá akumulátorová funkce. Vyžaduje dva parametry: hodnotu akumulátoru a položku ze sekvence, která se zpracuje s hodnotou akumulátoru. Počáteční hodnota akumulátoru se nazývá počáteční hodnota a musí být poskytována agregačnímu operátoru. Funkce akumulátoru vrátí novou hodnotu akumulátoru při každém volání. Nová hodnota akumulátoru se pak použije s dalším voláním funkce akumulátoru ke zpracování položky v sekvenci. Tato volání budou pokračovat až do konce sekvence.

Agregační operátor vrátí pozorovatelnou sekvenci, která je stejného typu jako počáteční hodnota předaná do operátoru. Chcete-li získat konečnou agregační hodnotu, přihlásíte se k odběru pozorovatelné sekvence vrácené z operátoru agregace. Jakmile je funkce akumulátoru použita v celé sekvenci, jsou volány obslužné rutiny OnNext a OnCompleted pozorovatele, které jsou součástí předplatného, aby poskytly konečnou agregační hodnotu. Podívejte se na příklad kódu poskytnutého s tímto operátorem.

Příklady

Tento příklad ukazuje použití operátoru agregace k počítání samohlásek v řetězci znaků vygenerovaných za běhu pomocí Console.Readkey(). Funkce CountVowels je akumulátorová funkce, která zvýší počet jednotlivých samohlásek zjištěných v sekvenci.

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

Tady je příklad výstupu z ukázkového kódu.

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

Viz také

Reference

Pozorovatelná třída

Agregovat přetížení

System.Reactive.Linq – obor názvů