Observable.GroupBy<TSource、TKey、TElement> メソッド (IObservable<TSource>、Func<TSource、TKey>、Func<TSource、TElement>)

監視可能なシーケンスの要素をグループ化し、指定した関数を使用して結果の要素を選択します。

Namespace:System.Reactive.Linq
アセンブリ: System.Reactive (System.Reactive.dll)

構文

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

型パラメーター

  • TSource
    型のソース。
  • TKey
    型キー。
  • TElement
    type 要素。

パラメーター

  • source
    種類: System.IObservable<TSource>
    要素をグループ化する監視可能なシーケンス。
  • keySelector
    種類: System.Func<TSource、TKey>
    各要素のキーを抽出する関数。
  • elementSelector
    種類: System.Func<TSource、TElement>
    各ソース要素を監視可能なグループ内の要素にマップする関数。

戻り値

種類: System.IObservable<IGroupedObservable<TKey、TElement>>
同じキー値を共有するすべての要素を含む、一意のキー値に対応する監視可能なグループのシーケンス。

使用上の注意

Visual Basic および C# では、 IObservable<TSource> 型の任意のオブジェクトでインスタンス メソッドとしてこのメソッドを呼び出すことができます。 インスタンス メソッド構文を使用してこのメソッドを呼び出す場合は、最初のパラメーターを省略します。 詳細については、」または」を参照してください。

解説

GroupBy 演算子は、キー値に基づいて項目のソース シーケンスをグループ化するために使用されます。 各キー値は keySelector 関数の結果であり、ソース シーケンス内の各項目から派生できます。 GroupBy 演算子の結果は、 IGroupedObservable<TKey、TElement> のシーケンスで表されるグループ化された項目のシーケンスです。 IGroupedObservable は、グループ化されたシーケンスを識別するキー プロパティを公開します。 グループ化されたシーケンスの実際の項目は、各ソース項目に適用される elementSelector 関数の結果によって制御されます。

このコード例では、過去 6 時間以内に発生したイベント ログ レコードのシーケンスを生成します。 GroupBy 演算子は LINQ ステートメントと共に使用され、LevelDisplayName プロパティに基づいてエラーであるイベント レコードをグループ化し、"Error" または "Critical" に評価します。 これが true の場合、キー セレクター関数の結果は true になり、その結果、イベント レコードがエラー グループにグループ化されます。 GroupBy 演算子の結果は、IGroupedObservable<Boolean EventRecord です>。 この一連の IGroupedObservable は、グループ化されたエラー イベント ログ エントリにアクセスするためにサブスクライブされます。 このコードでは、グループのシーケンスを調べて、キー値が true のグループを見つけます。 true のキー値は、エラー グループを識別します。 その後、そのエラー グループがサブスクライブされ、エラー イベント ログ エントリがコンソール ウィンドウに書き込まれます。

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

コード例を使用して、次の出力が生成されました。

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.

参照

リファレンス

Observable クラス

GroupBy オーバーロード

System.Reactive.Linq 名前空間