I have an observable sequence of elements that have a char Key
property, that has values in the range from 'A'
to 'E'
. I want to group these elements based on this key. After grouping them I want the result to by an observable of groups, so that I can process each group separately. My problem is that I can't find a nice way to preserve the key of each group in the final observable. Here is an example of what I am trying to do:
var observable = Observable
.Interval(TimeSpan.FromMilliseconds(100))
.Take(42)
.GroupBy(n => (char)(65 + n % 5))
.Select(grouped => grouped.ToArray())
.Merge();
observable.Subscribe(group =>
Console.WriteLine($"Group: {String.Join(", ", group)}"));
Output:
Group: 0, 5, 10, 15, 20, 25, 30, 35, 40
Group: 1, 6, 11, 16, 21, 26, 31, 36, 41
Group: 2, 7, 12, 17, 22, 27, 32, 37
Group: 3, 8, 13, 18, 23, 28, 33, 38
Group: 4, 9, 14, 19, 24, 29, 34, 39
The groups are correct, but the keys ('A'
- 'E'
) are lost. The type of the observable
is IObservable<long[]>
. What I would like it to
be instead, is an IObservable<IGrouping<char, long>>
. This way the group.Key
would be available inside the final subscription code. But as far as I can see
there is no built-in way to convert an IGroupedObservable
(the result of the GroupBy
operator) to an IGrouping
. I can see the operators ToArray
,
ToList
, ToLookup
, ToDictionary
etc, but not a ToGrouping
operator. My question is, how can I implement this operator?
Here is my incomplete attempt to implement it:
public static IObservable<IGrouping<TKey, TSource>> ToGrouping<TKey, TSource>(
this IGroupedObservable<TKey, TSource> source)
{
return Observable.Create<IGrouping<TKey, TSource>>(observer =>
{
// What to do?
return source.Subscribe();
});
}
My intention is to use it in the original example instead of the ToArray
, like this:
.Select(grouped => grouped.ToGrouping())
ValueTuple<TKey, TSource[]
is less satisfying than working with the semantically meaningfulIGrouping<TKey, TSource>
! 😃 – Anglocatholic