|
| 1 | +--- |
| 2 | +packages: |
| 3 | +- id: RangedObservableCollection |
| 4 | + version: 1.0.0 |
| 5 | +uti: com.xamarin.workbook |
| 6 | +id: 771a62d0-9764-4e3a-8642-1ae7ba5ad16a |
| 7 | +title: RangedObservableCollection |
| 8 | +platforms: |
| 9 | +- Console |
| 10 | +--- |
| 11 | + |
| 12 | +```csharp |
| 13 | +#r "System.Collections.ObjectModel.RangedObservableCollection" |
| 14 | +``` |
| 15 | + |
| 16 | +# RangedObservableCollection |
| 17 | + |
| 18 | +A small extension to ObservableCollection that allows for multiple items to be added, removed or replaced in a single operation. |
| 19 | + |
| 20 | +Like with all .NET libraries, we first need to add the using statement: |
| 21 | + |
| 22 | +```csharp |
| 23 | +using System.Collections.ObjectModel; |
| 24 | +``` |
| 25 | + |
| 26 | +Now that is done, we can instantiate the collection: |
| 27 | + |
| 28 | +```csharp |
| 29 | +var collection = new RangedObservableCollection<int>(); |
| 30 | +``` |
| 31 | + |
| 32 | +Because this collection acts just like any ObservableCollection, there is not much to show… except for the awesome fact that adding a whole collection of items no longer meas that you get a whole lot of events. To show this, we are going to attach an event handler and print to the console each time there is an update: |
| 33 | + |
| 34 | +```csharp |
| 35 | +collection.CollectionChanged += (s, e) => |
| 36 | +{ |
| 37 | + Console.WriteLine ("Event raised!"); |
| 38 | +}; |
| 39 | +``` |
| 40 | + |
| 41 | +First we want to show the old way of doing things: |
| 42 | + |
| 43 | +```csharp |
| 44 | +var itemsToAdd = new [] { 1, 2, 3, 4, 5 }; |
| 45 | +foreach (var item in itemsToAdd) |
| 46 | +{ |
| 47 | + collection.Add(item); |
| 48 | +} |
| 49 | +``` |
| 50 | + |
| 51 | +Whoah! We just broke our UI (or rather we did a whole lot of work that was not necessary). Instead, we should be doing this: |
| 52 | + |
| 53 | +```csharp |
| 54 | +var itemsToAdd = new [] { 1, 2, 3, 4, 5 }; |
| 55 | +collection.AddRange(itemsToAdd); |
| 56 | +``` |
| 57 | + |
| 58 | +Boom! Only a single event and our UI is happy! Not only can we add in bulk, we can remove a whole lot of items in one go too: |
| 59 | + |
| 60 | +```csharp |
| 61 | +var itemsToRemove = new [] { 1, 2, 3, 4, 5 }; |
| 62 | +collection.RemoveRange(itemsToRemove); |
| 63 | +``` |
| 64 | + |
| 65 | +Again, just a single event. Finally, we can replace all the items in the collection in a single action, without having to clear the collections first: |
| 66 | + |
| 67 | +```csharp |
| 68 | +var itemsToAdd = new [] { 1, 2, 3, 4, 5 }; |
| 69 | +collection.ReplaceRange(itemsToAdd); |
| 70 | +``` |
| 71 | + |
| 72 | +As you can see, just a single event. Now go forth and conquer! |
0 commit comments