forked from PeteGoo/ReactiveUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollectionExtensions.cs
More file actions
82 lines (76 loc) · 3.03 KB
/
CollectionExtensions.cs
File metadata and controls
82 lines (76 loc) · 3.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
namespace ReactiveUI
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reactive.Linq;
public static class CollectionExtensions
{
/// <summary>
/// Returns an observable sequence of the source collection change notifications.
/// Returns Observable.Never for collections not implementing INCC.
/// </summary>
/// <param name="source">Collection to observe.</param>
/// <returns>Observable sequence.</returns>
public static IObservable<NotifyCollectionChangedEventArgs> ObserveCollectionChanged(
this IEnumerable source)
{
var notifying = source as INotifyCollectionChanged;
if (notifying != null) {
return Observable.FromEventPattern<
NotifyCollectionChangedEventHandler,
NotifyCollectionChangedEventArgs>(
ev => notifying.CollectionChanged += ev,
ev => notifying.CollectionChanged -= ev)
.Select(x => x.EventArgs);
}
return Observable.Never<NotifyCollectionChangedEventArgs>();
}
/// <summary>
/// Returns an observable sequence of the source collection item property change notifications.
/// Returns Observable.Never for collections not implementing INCC.
/// </summary>
/// <param name="source">Collection to observe.</param>
/// <returns>Observable sequence.</returns>
public static IObservable<IObservedChange<T, object>> ObserveCollectionItemChanged<T>(
this IEnumerable source)
{
var notifying = source as IReactiveCollection<T>;
if (notifying != null)
{
return notifying.ItemChanged;
}
return Observable.Never<IObservedChange<T, object>>();
}
/// <summary>
/// Sorts the specified list in place using the comparer.
/// </summary>
/// <param name="list">List to sort.</param>
/// <param name="comparer">Comparer to use. If null, default comparer is used.</param>
public static void Sort<T>(
this IList<T> list,
IComparer<T> comparer = null)
{
comparer = comparer ?? Comparer<T>.Default;
var array = new T[list.Count];
list.CopyTo(array, 0);
Array.Sort(array, comparer);
for (var i = 0; i < array.Length; i++) {
list[i] = array[i];
}
}
/// <summary>
/// Finds an index of the specified value in the specified collection.
/// </summary>
public static int BinarySearch<T>(
this ICollection<T> collection,
T value,
IComparer<T> comparer = null)
{
var array = new T[collection.Count];
collection.CopyTo(array, 0);
return Array.BinarySearch(array, value, comparer);
}
}
}