Repository navigation
Tutorial6.en
This section introduces the collections developed as part of this library.
- ObservableMirrorCollection
- ObservableFilterSortMirrorCollection
- ObservableCombinableCollection
- PropertyTrackingCollection
- ImitableCollection
- ListAligner
- ICollectionAddRemoveObserver
A proxy collection that converts each element of a source collection of <T> into its corresponding <U> value and behaves as a collection of <U>.
Changes to the source collection, such as additions and removals, are reflected in this collection, keeping the corresponding elements synchronized.
If the IEnumerable<T> source specified in the constructor does not implement INotifyCollectionChanged,
changes such as additions and removals will not be reflected.
public interface IObservableMirrorCollection<T>
: IReadOnlyList<T>,
INotifyCollectionChanged,
INotifyPropertyChanged,
IDisposable {
}
public class ObservableMirrorCollection<T, U>
: ReadOnlyObservableCollection<U>, IObservableMirrorCollection<U> {
public ObservableMirrorCollection(
IEnumerable<T> source,
Func<T, U> convert,
Func<T, U, bool> equality,
Action<U>? removedHandler = null) { }
}
public class ObservableMirrorCollection<T>
: ObservableMirrorCollection<T, T> {
public ObservableMirrorCollection(
IEnumerable<T> source,
Action<T>? addingAction = null,
Action<T>? removedAction = null,
IEqualityComparer<T>? equality = null) { }
}
public static class EnumerableExtensions{
public static ObservableMirrorCollection<U> ToObservableMirror<T,U>(
this IEnumerable<T> self, Func<T,U> convert, Func<T,U,bool> equality, Action<U>? removedHandler = null) { }
public static ObservableMirrorCollection<T> ToObservableMirror<T>(
this IEnumerable<T> self) { }
}The following example demonstrates how to use it.
var srcList = new ObservableCollection<char>("ABCDEFG".ToCharArray());
var mrrList = new ObservableMirrorCollection<char, string>(
srcList,
x => x.ToString().ToLower(),
(chr, str) => chr.ToString().ToLower() == str);
Console.WriteLine($"source:{string.Join(",", srcList)}");
//source:A,B,C,D,E,F,G
Console.WriteLine($"mirror:{string.Join(",", mrrList)}");
//mirror:a,b,c,d,e,f,g
srcList.Add('X');
srcList.Move(1, 0);
srcList.Remove('F');
Console.WriteLine($"source:{string.Join(",", srcList)}");
//source:B,A,C,D,E,G,X
Console.WriteLine($"mirror:{string.Join(",", mrrList)}");
//mirror:b,a,c,d,e,g,x
//Unsubscribe from the collection change notifications
mrrList.Dispose();ObservableMirrorCollection<char,string> can be used as an IEnumerable<string>.
After use, dispose of the collection to unsubscribe from collection change notifications.
The elements themselves are not removed when the collection is disposed. Therefore, the action specified by removedAction is not executed.
If the converted elements require disposal, dispose of each element separately.
var srcList = new ObservableCollection<char>("ABCDE".ToCharArray());
var proxy1 = srcList.ToObservableMirror(
x => x.ToString(),
(chr, str) => chr.ToString() == str,
rm => Console.WriteLine($"{rm} removed."));
srcList.Remove('A');
//A removed
//Unsubscribe from the collection change notifications
proxy1.Dispose();
//
var proxy2 = srcList.ToObservableMirror(
x => new DisposableNamedObj() { Name = x.ToString() },
(s, d) => s.ToString() == d.Name,
d => d.Dispose());
srcList.Remove('B');
//B Dispose
proxy2.CombineDisposables().Dispose();
/*
C Dispose
D Dispose
E Dispose
*/
//Unsubscribe from the collection change notifications
proxy2.Dispose();
//The CombineDisposablesAndSelf() extension method allows you to dispose of each element and unsubscribe from the source collection at the same time.
var srcList = new ObservableCollection<char>("ABC".ToCharArray());
var proxy3 = srcList.ToObservableMirror(
chr => new DisposableNamedObj() { Name = chr.ToString() },
(chr, obj) => chr.ToString() == obj.Name,
obj => obj.Dispose());
srcList.Remove('A');
//A Dispose
//Dispose each elements and Unsubscribe from the collection change notifications
proxy3.CombineDisposablesAndSelf().Dispose();
//B Dispose
//C Dispose
srcList.Add('D');
//This collection extends ObservableMirrorCollection with filtering and sorting capabilities.
public class ObservableFilterSortMirrorCollection<T> : ObservableMirrorCollection<T>{
//constructor
public ObservableFilterSortMirrorCollection(IEnumerable<T> source, IEqualityComparer<T>? equality = null){ }
public void FilterBy(Func<T, bool> filterFunc, Expression<Func<T, object>> triggerProperty, params Expression<Func<T, object>>[] triggerProperties);
public void FilterBy(Func<T, bool> filterFunc);
public void FilterProperty(Expression<Func<T,bool>> filterProperty);
public void ClearFilter();
public void SortBy<TKey>(Func<T, TKey> getComparerKey, Expression<Func<T, object>> triggerProperty, params Expression<Func<T, object>>[] triggerProperties)
where TKey : IComparable<TKey>;
public void SortBy<TKey>(Func<T, TKey> getComparerKey, IComparer<TKey>? keyComparer = null, params Expression<Func<T, object>>[] triggerProperties);
public void SortProperty<TKey>(Expression<Func<T, TKey>> keyProperty, IComparer<TKey>? keyComparer = null);
public void ClearSort();
}Filtering and sorting are applied using the functions specified by FilterBy and SortBy.
If the collection elements implement INotifyPropertyChanged, the filter or sort is reevaluated whenever a property specified by an Expression changes.
You can specify multiple properties using the params argument to respond to changes in multiple property notifications.
Properties can also be specified using nested expressions, such as x=>x.Property1.Property2.Value.
In this case, the values of both Property1 and Property2 must implement INotifyPropertyChanged.
The following code applies filtering and sorting to the source collection.
var rmd = new Random();
var srcList = new ObservableCollection<int>(Enumerable.Range(0,5).Select(x=> rmd.Next(100)));
var mrrList = srcList.ToObservableFilterSortMirror();
Console.WriteLine($"source:{string.Join(",", srcList)}");
Console.WriteLine($"mirror:{string.Join(",", mrrList)}");
//source:92,32,90,13,83
//mirror:92,32,90,13,83
mrrList.SortBy(x => x);
Console.WriteLine($"mirror:{string.Join(",", mrrList)}");
//mirror:13,32,83,90,92
mrrList.FilterBy(x => 30 < x);
Console.WriteLine($"mirror:{string.Join(",", mrrList)}");
//mirror:32,83,90,92
srcList.Add(rmd.Next(100));//add element
Console.WriteLine($"mirror:{string.Join(",", mrrList)}");
//mirror:31,32,83,90,92
mrrList.ClearSorts();
Console.WriteLine($"mirror:{string.Join(",", mrrList)}");
//mirror:92,32,90,83,31
mrrList.ClearFilter();
Console.WriteLine($"mirror:{string.Join(",", mrrList)}");
//mirror:92,32,90,13,83,31
// after use
mrrList.Dispose();The following code filters the collection using properties of its elements.
public class ItemData : NotifyObjA {
public string Name {
get => Properties.GetValue("No name");
set => Properties.TrySetValue(value);
}
public int Number {
get => Properties.GetValue(0);
set => Properties.TrySetValue(value);
}
public bool IsActive {
get => Properties.GetValue<bool>();
set => Properties.TrySetValue(value);
}
public override string ToString() {
return $"Name:{this.Name}, Number:{Number}, IsActive:{IsActive}";
}
}var srcList = new ObservableCollection<ItemData>() {
new ItemData(){ Name = "Alice", Number = 50, IsActive = true },
new ItemData(){ Name = "Bob", Number = 30, IsActive = true },
new ItemData(){ Name = "Charlie", Number = 25, IsActive = false },
new ItemData(){Name = "Diana", Number = 42, IsActive = true},
new ItemData(){Name = "Eve", Number = 28, IsActive = false},
new ItemData(){Name = "Frank", Number = 35, IsActive = true},
new ItemData(){Name = "Grace", Number = 22, IsActive = false},
new ItemData(){Name = "Hank", Number = 60, IsActive = true},
new ItemData(){Name = "Ivy", Number = 33, IsActive = false}
};
var mrrList = srcList.ToObservableFilterSortMirror();
mrrList.FilterBy(x => x.IsActive && 30 < x.Number, x=>x.IsActive,x=>x.Number);
foreach(var p in mrrList) {
Console.WriteLine(p);
}
/*
Name:Alice, Number:50, IsActive:True
Name:Diana, Number:42, IsActive:True
Name:Frank, Number:35, IsActive:True
Name:Hank, Number:60, IsActive:True
*/
srcList.First(x => x.Name == "Alice").IsActive = false;
foreach(var p in mrrList) {
Console.WriteLine(p);
}
/*
Name:Diana, Number:42, IsActive:True
Name:Frank, Number:35, IsActive:True
Name:Hank, Number:60, IsActive:True
*/
mrrList.FilterProperty(x => x.IsActive);
foreach(var p in mrrList) {
Console.WriteLine(p);
}
/*
Name:Bob, Number:30, IsActive:True
Name:Diana, Number:42, IsActive:True
Name:Frank, Number:35, IsActive:True
Name:Hank, Number:60, IsActive:True
*/
//after use
mrrList.Dispose();A class for combining collections that implement INotifyCollectionChanged.
Collections that do not implement this interface can also be combined, but their changes will not be reflected.
public class ObservableCombinableCollection<T> : ObservableMirrorCollection<T> {
public ObservableCombinableCollection(Action<T>? addingAction = null, Action<T>? removedAction = null, IEqualityComparer<T>? equality = null);
public bool AppendCollection(IEnumerable<T> collection) { }
public bool InsertCollection(int index, IEnumerable<T> collection) { }
public bool RemoveCollection(IEnumerable<T> collection) { }
public void ClearCollections() { }
}var obs1List = new ObservableCollection<string>("ABC".Select(x => x.ToString()));
var obs2List = new ObservableCollection<string>("efg".Select(x=>x.ToString()));
var cmbList = new ObservableCombinableCollection<string>();
cmbList.CollectionChanged += (s, e) => {
Console.Write($"action:{e.Action}, ");
Console.Write($"OldIndex:{e.OldStartingIndex}, ");
Console.Write($"OldItems:{string.Join(" ", e.OldItems?.OfType<string>() ?? Array.Empty<string>())}, ");
Console.Write($"NewIndex:{e.NewStartingIndex}, ");
Console.Write($"NewItems:{string.Join(" ", e.NewItems?.OfType<string>() ?? Array.Empty<string>())} \n");
};
cmbList.AppendCollection(obs1List);
/*
action:Add, OldIndex:-1, OldItems:, NewIndex:0, NewItems:A
action:Add, OldIndex:-1, OldItems:, NewIndex:1, NewItems:B
action:Add, OldIndex:-1, OldItems:, NewIndex:2, NewItems:C
*/
cmbList.AppendCollection(obs2List);
/*
action:Add, OldIndex:-1, OldItems:, NewIndex:3, NewItems:e
action:Add, OldIndex:-1, OldItems:, NewIndex:4, NewItems:f
action:Add, OldIndex:-1, OldItems:, NewIndex:5, NewItems:g
*/
Console.WriteLine(string.Join(",", cmbList));
//A,B,C,e,f,g
obs1List.Remove("C");
//action:Remove, OldIndex:2, OldItems:C, NewIndex:-1, NewItems:
Console.WriteLine(string.Join(",", cmbList));
//A,B,e,f,g
obs1List[1] = "D";
//action:Replace, OldIndex:1, OldItems:B, NewIndex:1, NewItems:D
Console.WriteLine(string.Join(",", cmbList));
//A,D,e,f,g
obs2List.Move(0, 1);
//action:Move, OldIndex:2, OldItems:e, NewIndex:3, NewItems:e
Console.WriteLine(string.Join(",", cmbList));
//A,D,f,e,g
obs2List.Clear();
/*
action:Remove, OldIndex:2, OldItems:f, NewIndex:-1, NewItems:
action:Remove, OldIndex:2, OldItems:e, NewIndex:-1, NewItems:
action:Remove, OldIndex:2, OldItems:g, NewIndex:-1, NewItems:
*/
Console.WriteLine(string.Join(",", cmbList));
//A,D
//after use
cmbList.Dispose();Subscribes to property change notifications for each element in the specified collection.
If the collection implements INotifyCollectionChanged, additions and removals of elements are reflected in the set of tracked elements.
If a property value implements INotifyPropertyChanged, property paths can be nested.
public class PropertyTrackingCollection<T> : IReadOnlyList<T>, IDisposable, INotifyCollectionChanged {
//constructor
public PropertyTrackingCollection(IEnumerable<T> items);
public event NotifyCollectionChangedEventHandler? CollectionChanged;
public event Action<T, ChainedPropertyChangedEventArgs<object>>? TrackingPropertyChanged;
public IDisposable TrackHandler(Expression<Func<T, object>> property, Action<T, ChainedPropertyChangedEventArgs<object>> handle);
public TrackingPropertyList<T> CreateTrackingList();
}
public class TrackingPropertyList<T> : IEnumerable<Expression<Func<T,object>>>, IDisposable {
public void Register(Expression<Func<T, object>> property);
public void Remove(Expression<Func<T, object>> property);
public void Clear();
public void Dispose();
public IDisposable AttachHandler(Action<T, ChainedPropertyChangedEventArgs<object>> handle);
}There are two ways to register properties to track and subscribe to their change notifications:
- Register and subscribe using
TrackHandler(). - Obtain a
TrackingPropertyList, register properties usingRegister(), and subscribe usingAttachHandler().
By subscribing to the TrackingPropertyChanged event, you can receive all notifications registered through TrackHandler() and TrackingPropertyList.Register().
The following code tracks changes to the grandparent of each node.
var nds = "ABCDE".ToCharArray().ToDictionary(x => x, x => new ObservableNamedNode() { Name = x.ToString()});
var trackings = new PropertyTrackingCollection<ObservableNamedNode>(nds.Values);
var disp = trackings.TrackHandler(
x => x.Parent.Parent,
(s,e) => Console.WriteLine($"GrandParent changed, sender:{s.Name}, Property:{e.ChainedName}, G-parent:{e.PropertyValue ?? "null"}"));
var root = nds.Values.AssembleAsNAryTree(2);
//GrandParent changed, sender:D, Property:Parent.Parent, G-parent:A
//GrandParent changed, sender:E, Property:Parent.Parent, G-parent:A
Console.WriteLine(root.ToTreeDiagram(x => $"{x.Name}"));
/*
A
├ B
│ ├ D
│ └ E
└ C
*/
nds['A'].AddChild(nds['E']);
//GrandParent changed, sender:E, Property:Parent.Parent, G-parent:null
Console.WriteLine(root.ToTreeDiagram(x => $"{x.Name}"));
/*
A
├ B
│ └ D
├ C
└ E
*/
//after use
trackings.Dispose();With the TrackHandler method described above, the property to track and its handler are registered or unregistered together. Using TrackingPropertyList allows them to be registered or unregistered separately.
A property that has already been registered will not be registered again.
Disposing of the list also disposes its handlers.
var data = new ObservableCollection<ItemData>() {
new(){ Name = "Alice", Number = 50, IsActive = true },
new(){ Name = "Bob", Number = 30, IsActive = true },
new(){ Name = "Charlie", Number = 25, IsActive = false },
new(){ Name = "Diana", Number = 42, IsActive = true},
new(){ Name = "Eve", Number = 28, IsActive = false},
};
var trackings = new PropertyTrackingCollection<ItemData>(data);
var trcList = trackings.CreateTrackingList();
trcList.AttachHandler((s, e)
=> Console.WriteLine($"Property changed:{e.PropertyName}, Name:{s.Name}, Number:{s.Number}, IsActive:{s.IsActive}"));
trcList.Register(x => x.Number);
data[0].Number = 30;
//Property changed:Number, Name:Alice, Number:30, IsActive:True
data[1].IsActive = false;
//
trcList.Clear();
trcList.Register(x => x.IsActive);
data[0].Number = 33;
//
data[1].IsActive = true;
//Property changed:IsActive, Name:Bob, Number:30, IsActive:True
//after use
trackings.Dispose();This event receives all notifications registered through TrackHandler() and TrackingPropertyList.Register().
The following code subscribes to the TrackingPropertyChanged event.
The Number property is registered through TrackHandler, while the Number and IsActive properties are registered through TrackingPropertyList.
var data = new ObservableCollection<ItemData>() {
new(){ Name = "Alice", Number = 50, IsActive = true },
new(){ Name = "Bob", Number = 30, IsActive = true },
new(){ Name = "Charlie", Number = 25, IsActive = false },
};
var trackings = new PropertyTrackingCollection<ItemData>(data);
trackings.TrackingPropertyChanged += (s, e) => {
Console.WriteLine($"Handle all, Property:{e.ChainedName} Name:{s.Name}, Number:{s.Number}, IsActive:{s.IsActive}");
};
trackings.TrackHandler(x => x.Number, (s, e) => { });
var trcList = trackings.CreateTrackingList();
trcList.Register(x => x.IsActive);
trcList.Register(x => x.Number);
data[0].Number = 30;
//Handle all, Property:Number Name:Alice, Number:30, IsActive:True
//Handle all, Property:Number Name:Alice, Number:30, IsActive:True
data[1].IsActive = false;
//Handle all, Property:IsActive Name:Bob, Number:30, IsActive:False
trackings.Dispose();Converts each element of a source collection of <TSrc> into its corresponding <TDst> value and behaves as a collection of <TDst>.
public abstract class ImitableCollection
: INotifyPropertyChanged, INotifyCollectionChanged, IDisposable, IEnumerable {
/// <summary>If not in synchronization state, starts synchronization.</summary>
public abstract void Imitate();
/// <summary>Stops synchronization.</summary>
public abstract void Pause();
/// <summary>Stops synchronization and clears the imitable collection.</summary>
public abstract void ClearAndPause();
/// <summary>Indicates whether the current state is in synchronization.</summary>
public abstract bool IsImitating { get; }
}
public abstract class ImitableCollection<TDst>
: ImitableCollection,IObservableMirrorCollection<TDst> {
public abstract TDst this[int index] { get; }
public abstract int Count { get; }
}
public static class EnumerableExtensions{
/// <summary>Assists in initializing an instance.</summary>
/// <typeparam name="TSrc">The type of elements in the source collection for synchronization.</typeparam>
/// <typeparam name="TDst">The type of elements in the target imitable collection.</typeparam>
/// <param name="source">The source collection for synchronization.</param>
/// <param name="convert">A function to convert elements from <typeparamref name="TSrc"/> to corresponding <typeparamref name="TDst"/>.</param>
/// <param name = "removedAction" > Action to be performed when an element is removed from the collection or this instance disposed.</param>
/// <param name="isImitate">Specifies whether to initialize in a synchronized state.</param>
public static ImitableCollection<TDst> ToImitable<TSrc, TDst>(this IEnumerable<TSrc> source, Func<TSrc, TDst> convert, Action<TDst>? removedAction = null, bool isImitate = true) {
return new ImitableCollection<TSrc,TDst>(source, convert, removedAction, isImitate);
}
}While the IsImitating property is true, changes to the source collection, such as additions and removals, are reflected, keeping the corresponding elements synchronized.
If the specified IEnumerable<TSrc> source does not implement INotifyCollectionChanged, you can call the Imitate method to apply changes.
The differences from ObservableMirrorCollection<T,U> are:
- No comparison between the source and destination elements is required when creating an instance.
- You can control when synchronization starts and stops.
-
removedActionis executed not only when the source collection changes, but also whenClearAndPause()orDispose()is called.
These are the three differences.
When comparing elements in the source collection, value types are compared by value and reference types by reference identity.
Because no comparison between the source and destination elements is required, unrelated values can be synchronized.
var rdm = new Random();
var nameList = new ObservableCollection<char>("ABCD".ToArray());
var imitList = nameList.ToImitable(x => rdm.Next(10));
Console.WriteLine(string.Join(",", nameList));
//A,B,C,D
Console.WriteLine(string.Join(",", imitList));
//5,4,5,7
nameList.Add('E');
Console.WriteLine(string.Join(",", nameList));
//A,B,C,D,E
Console.WriteLine(string.Join(",", imitList));
//5,4,5,7,4
nameList.Move(0, 1);
Console.WriteLine(string.Join(",", nameList));
//B,A,C,D,E
Console.WriteLine(string.Join(",", imitList));
//4,5,5,7,4
nameList[0] = 'F';
Console.WriteLine(string.Join(",", nameList));
//F,A,C,D,E
Console.WriteLine(string.Join(",", imitList));
//8,5,5,7,4Next, let's control pausing and resuming synchronization.
imitList.Pause();
nameList.Remove('F');
Console.WriteLine(string.Join(",", nameList));
//A,C,D,E
Console.WriteLine(string.Join(",", imitList));
//8,5,5,7,4
imitList.Imitate();
Console.WriteLine(string.Join(",", imitList));
//5,5,7,4
imitList.ClearAndPause();
Console.WriteLine(string.Join(",", imitList));
//
imitList.Imitate();
Console.WriteLine(string.Join(",", imitList));
//1,2,5,4
//after use
imitList.Dispose();The following code specifies a source collection that does not implement INotifyCollectionChanged.
var rdm = new Random();
//Collection whoes elements are reference types.
var lst = new List<string>("ABCD".ToArray().Select(x=>x.ToString()));
var imitList = lst.ToImitable(x => rdm.Next(10));
Console.WriteLine(string.Join(",", lst));
//A,B,C,D
Console.WriteLine(string.Join(",", imitList));
//9,7,0,3
lst.Remove("A");
lst.Remove("B");
lst.Add("A");
Console.WriteLine(string.Join(",", lst));
//C,D,A
Console.WriteLine(string.Join(",", imitList));
//9,7,0,3
imitList.Imitate();
Console.WriteLine(string.Join(",", lst));
//C,D,A
Console.WriteLine(string.Join(",", imitList));
//0,3,8Immediately after the List is modified, the ImitableCollection remains unchanged.
Calling Imitate() applies the changes.
Because the elements of List<string> are reference types, the newly added "A" is treated as a different element and is assigned a new random value.
The following code demonstrates what happens when elements are removed due to source collection changes, ClearAndPause(), and Dispose().
var srcList = new ObservableCollection<string>("ABC".ToCharArray().Select(x => x.ToString()));
var imitList = srcList.ToImitable(
x => new DisposableNamedObj() { Name = x },
obj => obj.Dispose());
srcList.Remove("A");
//A Dispose
srcList.Clear();
//B Dispose
//C Dispose
srcList.Add("D");
srcList.Add("E");
imitList.ClearAndPause();
//D Dispose
//E Dispose
imitList.Imitate();
imitList.Dispose();
//D Dispose
//E DisposeRearranges a modifiable collection into the specified order.
public class ListAligner<S,T,TList> where TList : IList<T> {
public ListAligner(TList editList, Func<S, T> convert, Func<S, T, bool> equality,
Action<TList, int, T>? insert = null,
Action<TList, int, T>? replace = null, Action<TList, int, int>? move = null,
Action<TList, int>? remove=null, Action<TList>? clear=null) {
}
/// <summary>Aligns the list according to the specified order.</summary>
/// <param name="order">A collection defining the desired order of elements in the list.</param>
public void AlignBy(IEnumerable<S> order) { }
}
public class ListAligner<T, TList> : ListAligner<T,T,TList> where TList : IList<T> {
public ListAligner(TList editList,
Action<TList, int, T>? insert = null, Action<TList, int, T>? replace = null,
Action<TList, int>? remove = null, Action<TList, int, int>? move = null,
Action<TList>? clear = null, IEqualityComparer<T>? comparer = null) { }
}
public static class EnumerableExtensions{
public static void AlignBy<T>(this IList<T> self,IEnumerable<T> sequence, IEqualityComparer<T>? equality = null) { }
public static void AlignBy<S,T>(this IList<T> self, IEnumerable<S> sequence,Func<S,T> convert, Func<S,T,bool> equality) { }
public static void AlignBy<T>(this ObservableCollection<T> self, IEnumerable<T> sequence, IEqualityComparer<T>? equality = null) { }
public static void AlignBy<S,T>(this ObservableCollection<T> self, IEnumerable<S> sequence,Func<S,T> convert,Func<S,T,bool> equality) { }
}Using ListAligner, the target IList or ObservableCollection is rearranged to match the specified order.
If duplicate elements are present, their relative order is not guaranteed; therefore, the operation is an unstable sort.
var lst = new List<string>(new string[] {"C","O","N","F","I","N"});
var algnr = new ListAligner<char, string, List<string>>(
lst,
c => c.ToString().ToUpper(),
(c, s) => Equals(c.ToString().ToUpper(), s));
Console.WriteLine(string.Join(",", lst));
//C,O,N,F,I,N
algnr.AlignBy("finance");
Console.WriteLine(string.Join(",", lst));
//F,I,N,A,N,C,E
algnr.AlignBy("finance".Reverse());
Console.WriteLine(string.Join(",", lst));
//E,C,N,A,N,I,FThe following code operates on an ObservableCollection and shows the operations performed along the way.
var obsLst = new ObservableCollection<string>(new string[] {"C","O","N","F","I","N"});
obsLst.CollectionChanged += (s, e) => {
Console.Write($"action:{e.Action}, ");
Console.Write($"OldIndex:{e.OldStartingIndex}, ");
Console.Write($"OldItems:{string.Join(" ", e.OldItems?.OfType<string>() ?? Array.Empty<string>())}, ");
Console.Write($"NewIndex:{e.NewStartingIndex}, ");
Console.Write($"NewItems:{string.Join(" ", e.NewItems?.OfType<string>() ?? Array.Empty<string>())} \n");
};
var algnr2 = new ListAligner<char, string, ObservableCollection<string>>(
obsLst,
c => c.ToString().ToUpper(),
(c, s) => Equals(c.ToString().ToUpper(), s),
move: (collection, i, j) => collection.Move(i, j));
Console.WriteLine(string.Join(",", obsLst));
//C,O,N,F,I,N
algnr2.AlignBy("finance");
/*
action:Move, OldIndex:0, OldItems:C, NewIndex:5, NewItems:C
action:Move, OldIndex:2, OldItems:F, NewIndex:0, NewItems:F
action:Remove, OldIndex:1, OldItems:O, NewIndex:-1, NewItems:
action:Move, OldIndex:2, OldItems:I, NewIndex:1, NewItems:I
action:Add, OldIndex:-1, OldItems:, NewIndex:3, NewItems:A
action:Add, OldIndex:-1, OldItems:, NewIndex:6, NewItems:E
*/
Console.WriteLine(string.Join(",", obsLst));
//F,I,N,A,N,C,E
algnr2.AlignBy("infinite");
/*
action:Move, OldIndex:0, OldItems:F, NewIndex:2, NewItems:F
action:Replace, OldIndex:3, OldItems:A, NewIndex:3, NewItems:I
action:Replace, OldIndex:5, OldItems:C, NewIndex:5, NewItems:I
action:Add, OldIndex:-1, OldItems:, NewIndex:6, NewItems:T
*/
Console.WriteLine(string.Join(",", obsLst));
//I,N,F,I,N,I,T,E
algnr2.AlignBy("finery");
/*
action:Move, OldIndex:0, OldItems:I, NewIndex:1, NewItems:I
action:Move, OldIndex:2, OldItems:F, NewIndex:0, NewItems:F
action:Move, OldIndex:1, OldItems:N, NewIndex:2, NewItems:N
action:Remove, OldIndex:3, OldItems:I, NewIndex:-1, NewItems:
action:Move, OldIndex:6, OldItems:E, NewIndex:3, NewItems:E
action:Replace, OldIndex:4, OldItems:N, NewIndex:4, NewItems:R
action:Replace, OldIndex:5, OldItems:I, NewIndex:5, NewItems:Y
action:Remove, OldIndex:6, OldItems:T, NewIndex:-1, NewItems:
*/
Console.WriteLine(string.Join(",", obsLst));
//F,I,N,E,R,YExtension methods are also provided.
When the target collection is an ObservableCollection, Move() is supplied by default as the operation used to move elements.
var obsLst = new ObservableCollection<string>("ABCD".Select(x=>x.ToString()));
obsLst.AlignBy("dcba",
x => x.ToString().ToUpper(),
(c, s) => Equals(c.ToString().ToUpper(), s));
/*
action:Move, OldIndex:0, OldItems:A, NewIndex:3, NewItems:A
action:Move, OldIndex:2, OldItems:D, NewIndex:0, NewItems:D
action:Move, OldIndex:1, OldItems:B, NewIndex:2, NewItems:B
*/
Console.WriteLine(string.Join(",", obsLst));
//D,C,B,AAn observer that captures elements added to or removed from a collection through collection change notifications.
public interface ICollectionAddRemoveObserver<out T> : IDisposable {
ICollectionAddRemoveObserver<T> Added(Action<T> added);
ICollectionAddRemoveObserver<T> Removed(Action<T> removed);
}
public static class ExtensionMethods{
public static ICollectionAddRemoveObserver<T> AddRemoveObserver<T>(this ObservableCollection<T> self) => new CollectionObserver<T>(self);
public static ICollectionAddRemoveObserver<T> AddRemoveObserver<T>(this ReadOnlyObservableCollection<T> self) => new CollectionObserver<T>(self);
public static ICollectionAddRemoveObserver<T> AddRemoveObserver<T>(this IObservableMirrorCollection<T> self) => new CollectionObserver<T>(self);
}You can easily capture elements added to or removed from a collection.
var list = new ObservableCollection<string>(new string[] {"A","B","C"});
IDisposable listener = list.AddRemoveObserver()
.Added(x => Console.WriteLine($"added : {x}"))
.Removed(x => Console.WriteLine($"removed : {x}"));
list.Add("D");
// added : D
Console.WriteLine(string.Join(",", list));
//A,B,C,D
list[0] = "E";
//adeed : E
//removed : A
Console.WriteLine(string.Join(",", list));
//E,B,C,D
list.Move(1, 2);
Console.WriteLine(string.Join(",", list));
//E,C,B,D
list.RemoveAt(0);
//removed : E
Console.WriteLine(string.Join(",", list));
//C,B,D
list.Clear();
//removed : C
//removed : B
//removed : D
Console.WriteLine(string.Join(",", list));
//
listener.Dispose();
list.Add("G");
//