Udostępnij za pośrednictwem


Observable.GroupBy<TSource, TKey, TElement> Method (IObservable<TSource, Func<TSource, TKey>, Func<TSource>, TElement>)

Grupuje elementy widocznej sekwencji i wybiera wynikowe elementy przy użyciu określonej funkcji.

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

Składnia

'Declaration
<ExtensionAttribute> _
Public Shared Function GroupBy(Of TSource, TKey, TElement) ( _
    source As IObservable(Of TSource), _
    keySelector As Func(Of TSource, TKey), _
    elementSelector As Func(Of TSource, TElement) _
) As IObservable(Of IGroupedObservable(Of TKey, TElement))
'Usage
Dim source As IObservable(Of TSource)
Dim keySelector As Func(Of TSource, TKey)
Dim elementSelector As Func(Of TSource, TElement)
Dim returnValue As IObservable(Of IGroupedObservable(Of TKey, TElement))

returnValue = source.GroupBy(keySelector, _
    elementSelector)
public static IObservable<IGroupedObservable<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
    this IObservable<TSource> source,
    Func<TSource, TKey> keySelector,
    Func<TSource, TElement> elementSelector
)
[ExtensionAttribute]
public:
generic<typename TSource, typename TKey, typename TElement>
static IObservable<IGroupedObservable<TKey, TElement>^>^ GroupBy(
    IObservable<TSource>^ source, 
    Func<TSource, TKey>^ keySelector, 
    Func<TSource, TElement>^ elementSelector
)
static member GroupBy : 
        source:IObservable<'TSource> * 
        keySelector:Func<'TSource, 'TKey> * 
        elementSelector:Func<'TSource, 'TElement> -> IObservable<IGroupedObservable<'TKey, 'TElement>> 
JScript does not support generic types and methods.

Parametry typu

  • Tsource
    Źródło typu.
  • Tkey
    Klucz typu.
  • Telement
    Element type.

Parametry

  • source
    Typ: System.IObservable<TSource>
    Obserwowana sekwencja, której elementy do grupowania.
  • keySelector
    Typ: System.Func<TSource, TKey>
    Funkcja wyodrębniania klucza do każdego elementu.
  • elementSelector
    Typ: System.Func<TSource, TElement>
    Funkcja mapowania każdego elementu źródłowego na element w widocznej grupie.

Wartość zwracana

Typ: System.IObservableIGroupedObservable<< TKey, TElement>>
Sekwencja obserwowanych grup, z których każda odpowiada unikatowej wartości klucza zawierającej wszystkie elementy, które współdzielą tę samą wartość klucza.

Uwaga dotycząca użycia

W języku Visual Basic i C#można wywołać tę metodę jako metodę wystąpienia w dowolnym obiekcie 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 GroupBy służy do grupowania sekwencji źródłowej elementów w grupy na podstawie wartości klucza. Każda wartość klucza jest wynikiem funkcji keySelector i może pochodzić z każdego elementu w sekwencji źródłowej. Wynikiem operatora GroupBy jest sekwencja pogrupowanych elementów reprezentowanych przez sekwencję IGroupedObservable<TKey, TElement>. Element IGroupedObservable uwidacznia właściwość klucza identyfikującą sekwencję grupowaną. Rzeczywiste elementy w wynikowych sekwencjach zgrupowanych są kontrolowane przez wynik funkcji elementSelector zastosowanej do każdego elementu źródłowego.

Przykłady

Ten przykładowy kod generuje sekwencję rekordów dziennika zdarzeń, które wystąpiły w ciągu ostatnich sześciu godzin. Operator GroupBy jest następnie używany z instrukcją LINQ do grupowania rekordów zdarzeń, które są błędami na podstawie właściwości LevelDisplayName oceniając wartość "Error" lub "Critical". Jeśli jest to prawda, wynik funkcji selektora kluczy ma wartość true, co powoduje zgrupowanie rekordu zdarzenia w grupie błędów. Wynikiem operatora GroupBy jest wartość logiczna IGroupedObservable<, EventRecord>. Ta sekwencja IGroupedObservable jest subskrybowana w celu uzyskania dostępu do pogrupowanych wpisów dziennika zdarzeń błędów. Kod analizuje sekwencję grup, aby znaleźć grupę, w której wartość klucza jest prawdziwa. Wartość klucza true identyfikuje grupę błędów. Ta grupa błędów jest następnie subskrybowana, a wpisy dziennika zdarzeń błędów są zapisywane w oknie konsoli.

using System;
using System.Reactive.Linq;
using System.Reactive.Concurrency;
using System.Diagnostics.Eventing.Reader;
using System.IO;

namespace Example
{
  class Program
  {
    static void Main()
    {
      //************************************************************************************************//
      //*** Generate a sequence of event log entries that have been written to the system event log  ***//
      //*** within the last 6 hours.                                                                 ***//
      //************************************************************************************************//

      const int eventLogTimeSpan = 6;
      EventLogReader sysEventLog = new EventLogReader("System");
      

      //****************************************************************************************************//
      //*** Start with the last entry in the event log.                                                  ***//
      //*** Stop on an event generated at a time more than the EventLogTimeSpan (6 hrs in this example). ***//
      //*** Each iteration function will step back one entry.                                            ***//
      //*** The resultSelector function will just select each entry for inclusion in the sequence.       ***//
      //*** The ThreadPool schedule schedules the processing of the event log on a thread pool thread    ***//
      //****************************************************************************************************//

      sysEventLog.Seek(SeekOrigin.End,0);
      EventRecord lastEntry = sysEventLog.ReadEvent();
      var eventLogEntrySeq = Observable.Generate(lastEntry,                                                      
                                                 x => (DateTime.Now - x.TimeCreated) < TimeSpan.FromHours(eventLogTimeSpan),  
                                                 x => {sysEventLog.Seek(x.Bookmark,-1); return sysEventLog.ReadEvent();},                          
                                                 x => x,                                                         
                                                 Scheduler.ThreadPool);                                          


      //************************************************************************************************************//
      //*** Use the GroupBy operator with LINQ to group the sequence into entries that are errors (key=true) and ***//
      //*** those that are not errors (key=false).                                                               ***//
      //************************************************************************************************************//

      var eventLogGroupedSeq =
        from entry in eventLogEntrySeq
        group entry by (entry.LevelDisplayName == "Error") || (entry.LevelDisplayName == "Critical") into groupedEntries
        select groupedEntries;


      //***************************************************************************************//
      //*** eventLogGroupedSeq is a IGroupedObservable<Boolean, EventRecord>. Subscribing   ***//
      //*** will return a sequence of the groups. For this example, we only want the group  ***//
      //*** where the key is true indicating the Error entries group. So we then subscribe  ***//
      //*** to that grouped sequence to write the error entries that occurred within the    ***//
      //*** last 6 hours.                                                                   ***//
      //***************************************************************************************//

      eventLogGroupedSeq.Subscribe(groupedSeq =>
      {
        if (groupedSeq.Key == true)
        {
          groupedSeq.Subscribe(evtEntry => Console.WriteLine("ID : {0}\n" +
                                                             "Type : {1}\n" + 
                                                             "Source: {2}\n" + 
                                                             "Time Generated: {3}\n" + 
                                                             "Message: {4}\n",
                                                             evtEntry.Id,
                                                             evtEntry.LevelDisplayName,
                                                             evtEntry.ProviderName,
                                                             evtEntry.TimeCreated.ToString(),
                                                             evtEntry.FormatDescription()));
        }  
      });

      Console.WriteLine("\nDisplaying error entries from the system event log\n" +
                        "that occurred within the last {0} hours...\n\n" +
                        "Press ENTER to exit...\n",eventLogTimeSpan);
      Console.ReadLine();
    }
  }
}

Następujące dane wyjściowe zostały wygenerowane przy użyciu przykładowego kodu.

Displaying error entries from the system event log
that occurred within the last 6 hours...

Press ENTER to exit...

ID : 34001
Type : Error
Source: Microsoft-Windows-SharedAccess_NAT
Time Generated: 5/31/2011 4:39:18 AM
Message: The ICS_IPV6 failed to configure IPv6 stack.

ID : 34001
Type : Error
Source: Microsoft-Windows-SharedAccess_NAT
Time Generated: 5/31/2011 4:01:36 AM
Message: The ICS_IPV6 failed to configure IPv6 stack.

ID : 34001
Type : Error
Source: Microsoft-Windows-SharedAccess_NAT
Time Generated: 5/31/2011 3:49:29 AM
Message: The ICS_IPV6 failed to configure IPv6 stack.

ID : 34001
Type : Error
Source: Microsoft-Windows-SharedAccess_NAT
Time Generated: 5/31/2011 3:11:47 AM
Message: The ICS_IPV6 failed to configure IPv6 stack.

ID : 34001
Type : Error
Source: Microsoft-Windows-SharedAccess_NAT
Time Generated: 5/31/2011 2:59:40 AM
Message: The ICS_IPV6 failed to configure IPv6 stack.

Zobacz też

Odwołanie

Obserwowana klasa

Przeciążenie Grupuj przez

Przestrzeń nazw System.Reactive.Linq