MaxBy.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if !NO_PERF
  3. using System;
  4. using System.Collections.Generic;
  5. namespace System.Reactive.Linq.ObservableImpl
  6. {
  7. class MaxBy<TSource, TKey> : Producer<IList<TSource>>
  8. {
  9. private readonly IObservable<TSource> _source;
  10. private readonly Func<TSource, TKey> _keySelector;
  11. private readonly IComparer<TKey> _comparer;
  12. public MaxBy(IObservable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
  13. {
  14. _source = source;
  15. _keySelector = keySelector;
  16. _comparer = comparer;
  17. }
  18. protected override IDisposable Run(IObserver<IList<TSource>> observer, IDisposable cancel, Action<IDisposable> setSink)
  19. {
  20. var sink = new _(this, observer, cancel);
  21. setSink(sink);
  22. return _source.SubscribeSafe(sink);
  23. }
  24. class _ : Sink<IList<TSource>>, IObserver<TSource>
  25. {
  26. private readonly MaxBy<TSource, TKey> _parent;
  27. private bool _hasValue;
  28. private TKey _lastKey;
  29. private List<TSource> _list;
  30. public _(MaxBy<TSource, TKey> parent, IObserver<IList<TSource>> observer, IDisposable cancel)
  31. : base(observer, cancel)
  32. {
  33. _parent = parent;
  34. _hasValue = false;
  35. _lastKey = default(TKey);
  36. _list = new List<TSource>();
  37. }
  38. public void OnNext(TSource value)
  39. {
  40. var key = default(TKey);
  41. try
  42. {
  43. key = _parent._keySelector(value);
  44. }
  45. catch (Exception ex)
  46. {
  47. base._observer.OnError(ex);
  48. base.Dispose();
  49. return;
  50. }
  51. var comparison = 0;
  52. if (!_hasValue)
  53. {
  54. _hasValue = true;
  55. _lastKey = key;
  56. }
  57. else
  58. {
  59. try
  60. {
  61. comparison = _parent._comparer.Compare(key, _lastKey);
  62. }
  63. catch (Exception ex)
  64. {
  65. base._observer.OnError(ex);
  66. base.Dispose();
  67. return;
  68. }
  69. }
  70. if (comparison > 0)
  71. {
  72. _lastKey = key;
  73. _list.Clear();
  74. }
  75. if (comparison >= 0)
  76. {
  77. _list.Add(value);
  78. }
  79. }
  80. public void OnError(Exception error)
  81. {
  82. base._observer.OnError(error);
  83. base.Dispose();
  84. }
  85. public void OnCompleted()
  86. {
  87. base._observer.OnNext(_list);
  88. base._observer.OnCompleted();
  89. base.Dispose();
  90. }
  91. }
  92. }
  93. }
  94. #endif