Repository navigation
Tutorial7.en
Categorizes added items in a tree structure.
public class CategoryTree<TItm, TCtg> {
/// <summary>Initializes a new instance.</summary>
/// <param name="items">The collection of items to be categorized.</param>
/// <param name="equality">The comparer to determine category equivalence.</param>
/// <param name="lv1Category">The function to determine the first-level category.</param>
/// <param name="nestsLvCategories">Functions to determine categories at subsequent levels.</param>
public CategoryTree(IEnumerable<TItm> items, IEqualityComparer<TCtg> equality, Func<TItm, TCtg> lv1Category, params Func<TItm, TCtg>[] nestsLvCategories) { }
public CategoryTree(IEnumerable<TItm> items, Func<TItm, TCtg> lv1Category, params Func<TItm, TCtg>[] nestsLvCategories){ }
public CategoryTree(IEqualityComparer<TCtg> equality, Func<TItm, TCtg> lv1Category, params Func<TItm, TCtg>[] nestsLvCategories){ }
public CategoryTree(Func<TItm, TCtg> lv1Category, params Func<TItm, TCtg>[] nestsLvCategories){ }
public Node Root { get; }
public void Add(TItm item) { }
public void Add(IEnumerable<TItm> items) { }
public void Remove(TItm item) { }
public void Remove(IEnumerable<TItm> items) { }
public void Clear() { }
public class Node : TreeNodeBase<Node> {
public new ReadOnlyObservableCollection<Node> Children { get; }
/// <summary>Gets the category assigned at the corresponding level.</summary>
public TCtg Category { get; }
/// <summary>Indicates whether this node represents an item or a category.</summary>
public bool HasItem { get; }
/// <summary>Gets the item represented by this node, if <see cref="HasItem"/> is true. Otherwise, returns the default value.</summary>
public TItm Item { get; }
}
}
The following code categorizes the added DateTime values in a tree structure by year, month, and day.
var lst = new List<DateTime>() {
new(2026,8,23),
new(2026,8,15),
new(2026,2,5),
new(2026,2,5),
};
var dateTree = new CategoryTree<DateTime, int>(x => x.Year, x => x.Month, x => x.Day);
dateTree.Add(lst);
Console.WriteLine(dateTree.Root.ToTreeDiagram(x => x.HasItem ? x.Item.ToString("yyyy/M/d") : x.Category.ToString()));
/*
0
└ 2026
├ 8
│ ├ 23
│ │ └ 2026/8/23
│ └ 15
│ └ 2026/8/15
└ 2
└ 5
├ 2026/2/5
└ 2026/2/5
*/
dateTree.Remove(lst[1]);
Console.WriteLine(dateTree.Root.ToTreeDiagram(x => x.HasItem ? x.Item.ToString("yyyy/M/d") : x.Category.ToString()));
/*
0
└ 2026
├ 8
│ └ 23
│ └ 2026/8/23
└ 2
└ 5
├ 2026/2/5
└ 2026/2/5
*/
dateTree.Add(new DateTime(2027,1,17));
Console.WriteLine(dateTree.Root.ToTreeDiagram(x => x.HasItem ? x.Item.ToString("yyyy/M/d") : x.Category.ToString()));
/*
0
├ 2026
│ ├ 8
│ │ └ 23
│ │ └ 2026/8/23
│ └ 2
│ └ 5
│ ├ 2026/2/5
│ └ 2026/2/5
└ 2027
└ 1
└ 17
└ 2027/1/17
*/Category nodes are also generated as items are added.
To sort each category, use the following wrapper.
public class CategoryView
: BindableTreeNodeWrapper<CategoryTree<DateTime, int>.Node, CategoryView>
, IComparable<CategoryView> {
public CategoryView(CategoryTree<DateTime, int>.Node sourceNode) : base(sourceNode) { }
protected override CategoryView GenerateChild(CategoryTree<DateTime, int>.Node sourceChildNode) {
return new CategoryView(sourceChildNode);
}
protected override IEnumerable<CategoryView> SetupPublicChildCollection(CombinableMirroredChildrenCollection<CategoryView> children) {
var lst = children.ToObservableFilterSortMirror();
lst.SortBy(x => x);
return lst;
}
public int CompareTo(CategoryView? other) {
if(HasItem) {
return this.Item.CompareTo(other?.Item);
} else {
return this.Category.CompareTo(other?.Category);
}
}
public int Category => Source.Category;
public bool HasItem => Source.HasItem;
public DateTime Item => Source.Item;
}The following code performs the same operations and displays the sorted wrapper.
var lst = new List<DateTime>() {
new(2026,8,23),
new(2026,8,15),
new(2026,2,5),
new(2026,2,5),
};
var dateTree = new CategoryTree<DateTime, int>(x => x.Year, x => x.Month, x => x.Day);
var dateTreeView = new CategoryView(dateTree.Root);
dateTree.Add(lst);
Console.WriteLine(dateTreeView.ToTreeDiagram(x => x.HasItem ? x.Item.ToString("yyyy/M/d") : x.Category.ToString()));
/*
0
└ 2026
├ 2
│ └ 5
│ ├ 2026/2/5
│ └ 2026/2/5
└ 8
├ 15
│ └ 2026/8/15
└ 23
└ 2026/8/23
*/
dateTree.Remove(lst[1]);
Console.WriteLine(dateTreeView.ToTreeDiagram(x => x.HasItem ? x.Item.ToString("yyyy/M/d") : x.Category.ToString()));
/*
0
└ 2026
├ 2
│ └ 5
│ ├ 2026/2/5
│ └ 2026/2/5
└ 8
└ 23
└ 2026/8/23
*/
dateTree.Add(new DateTime(2027,1,17));
Console.WriteLine(dateTreeView.ToTreeDiagram(x => x.HasItem ? x.Item.ToString("yyyy/M/d") : x.Category.ToString()));
/*
0
├ 2026
│ ├ 2
│ │ └ 5
│ │ ├ 2026/2/5
│ │ └ 2026/2/5
│ └ 8
│ └ 23
│ └ 2026/8/23
└ 2027
└ 1
└ 17
└ 2027/1/17
*/Monitors the specified properties and reclassifies items when those properties change.
ReactiveCategoryTree.cs
public class ReactiveCategoryTree<TItm, TCtg> : CategoryTree<TItm, TCtg>, IDisposable {
/// <summary> Initializes a new instance.</summary>
/// <param name="items">The collection of items to be categorized.</param>
/// <param name="properties">A collection of property expressions whose changes trigger category updates.</param>
/// <param name="equality">The comparer to determine category equivalence.</param>
/// <param name="lv1Category">The function to determine the first-level category.</param>
/// <param name="nestsLvCategories">Functions to determine categories at subsequent levels.</param>
public ReactiveCategoryTree(IEnumerable<TItm> items, ExpressionList<TItm> properties, IEqualityComparer<TCtg> equality, Func<TItm, TCtg> lv1Category, params Func<TItm, TCtg>[] nestsLvCategories){ }
public ReactiveCategoryTree(IEnumerable<TItm> items, IEnumerable<Expression<Func<TItm,object>>> properties, IEqualityComparer<TCtg> equality, Func<TItm, TCtg> lv1Category, params Func<TItm, TCtg>[] nestsLvCategories) { }
public ReactiveCategoryTree(IEnumerable<TItm> items,ExpressionList<TItm> properties,Func<TItm,TCtg> lv1Category,params Func<TItm,TCtg>[] nestsLvCategories){ }
public ReactiveCategoryTree(IEnumerable<TItm> items, IEnumerable<Expression<Func<TItm, object>>> properties, Func<TItm, TCtg> lv1Category, params Func<TItm, TCtg>[] nestsLvCategories){ }
public ReactiveCategoryTree(ExpressionList<TItm> properties, IEqualityComparer<TCtg> equality, Func<TItm, TCtg> lv1Category, params Func<TItm, TCtg>[] nestsLvCategories){ }
public ReactiveCategoryTree(IEnumerable<Expression<Func<TItm, object>>> properties, IEqualityComparer<TCtg> equality, Func<TItm, TCtg> lv1Category, params Func<TItm, TCtg>[] nestsLvCategories){ }
public ReactiveCategoryTree(ExpressionList<TItm> properties, Func<TItm, TCtg> lv1Category, params Func<TItm, TCtg>[] nestsLvCategories) { }
public ReactiveCategoryTree(IEnumerable<Expression<Func<TItm, object>>> properties, Func<TItm, TCtg> lv1Category, params Func<TItm, TCtg>[] nestsLvCategories){ }
public void Dispose(){ }
}ExpressionList<TItm> is provided to make it easier to specify the properties to monitor.
This allows you to omit the declaration of Expression<Func<TItm,object>>.
var ctgTree = new ReactiveCategoryTree<AnyNode, string>(
collection,
new Expression<Func<AnyNode,object>>[] { x => x.Prop1, x => x.Prop2 },
x => x.Prop1,
x => x.Prop2
);var ctgTree = new ReactiveCategoryTree<AnyNode, string>(
collection,
new(x => x.Prop1, x => Prop2),
x => x.Prop1,
x => x.Prop2
);The following code defines the Player class and the PlayerView class, which serves as a wrapper for the Node class.
public class Player : INotifyPropertyChanged {
public Player() {
this.Properties = new PropertyAccessor(this, () => this.PropertyChanged);
}
protected PropertyAccessor Properties { get; }
public event PropertyChangedEventHandler? PropertyChanged;
public string Name { get; set; }
public int Rank {
get => Properties.GetValue(0);
set => Properties.TrySetValue(value);
}
public TimeSpan ActivePeriod {
get => Properties.GetValue<TimeSpan>();
set => Properties.TrySetValue(value);
}
public override string ToString() {
return $"Name:{Name}, Rank:{Rank}, Period:{ActivePeriod.Days}";
}
}
public class PlayerView : BindableTreeNodeWrapper<CategoryTree<Player, int>.Node, PlayerView> {
Comparer<PlayerView> comparer;
public PlayerView(CategoryTree<Player, int>.Node sourceNode) : base(sourceNode) {
comparer = Comparer<PlayerView>.Create((a, b) => {
if (a.HasItem && b.HasItem)
return a.Item.ActivePeriod.Days - b.Item.ActivePeriod.Days;
else
return a.Category - b.Category;
});
}
protected override PlayerView GenerateChild(CategoryTree<Player, int>.Node sourceChildNode) {
return new PlayerView(sourceChildNode);
}
protected override IEnumerable<PlayerView> SetupPublicChildCollection(CombinableMirroredChildrenCollection<PlayerView> children) {
var lst = children.ToObservableFilterSortMirror();
if (this.Source.Depth() == 0) {
//Reverse the order of the root node's child node collection.
lst.SortBy(x => x, comparer.Invert());
} else {
lst.SortBy(x => x, comparer);
}
return lst;
}
public override string ToString() {
if(this.Source.HasItem) return this.Source.Item.ToString();
var header = this.Source.Depth() switch {
0 => "Ranker",
1 => toRankLabel(this.Source.Category) + "-Rank",
2 => $"{this.Source.Category} days",
_ => "",
};
return header;
}
string toRankLabel(int rank) {
string str = rank switch {
1 => "E",
2 => "D",
3 => "C",
4 => "B",
5 => "A",
_ => "_",
};
return str;
}
public int Category => Source.Category;
public bool HasItem => Source.HasItem;
public Player Item => Source.Item;
}The following code uses these classes to categorize the players and then changes some properties.
var lst = new List<Player>() {
new(){Name = "Ada", Rank = 2, ActivePeriod = new(32,0,0,0)},
new(){Name = "Bill", Rank = 5, ActivePeriod = new(75,0,0,0)},
new(){Name = "Curt", Rank = 2, ActivePeriod = new(41,0,0,0)},
new(){Name = "Dan", Rank = 4, ActivePeriod = new(87,0,0,0)},
new(){Name = "Eden", Rank = 1, ActivePeriod = new(13,0,0,0)},
new(){Name = "Fleur", Rank = 2, ActivePeriod = new(14,0,0,0)},
}.ToDictionary(x => x.Name, x => x);
var ctgTree = new ReactiveCategoryTree<Player, int>(
new(x => x.Rank, x => x.ActivePeriod),
x =>x.Rank ,
x => x.ActivePeriod.Days);
ctgTree.Add(lst.Values);
var ctgTreeView = new PlayerView(ctgTree.Root);
Console.WriteLine(ctgTreeView.ToTreeDiagram(x => x.ToString()));
/*
Ranker
├ A-Rank
│ └ 75 days
│ └ Name:Bill, Rank:5, Period:75
├ B-Rank
│ └ 87 days
│ └ Name:Dan, Rank:4, Period:87
├ D-Rank
│ ├ 14 days
│ │ └ Name:Fleur, Rank:2, Period:14
│ ├ 32 days
│ │ └ Name:Ada, Rank:2, Period:32
│ └ 41 days
│ └ Name:Curt, Rank:2, Period:41
└ E-Rank
└ 13 days
└ Name:Eden, Rank:1, Period:13
*/
lst["Curt"].Rank = 3;
lst["Fleur"].ActivePeriod = new(32, 0, 0, 0);
Console.WriteLine(ctgTreeView.ToTreeDiagram(x => x.ToString()));
/*
Ranker
├ A-Rank
│ └ 75 days
│ └ Name:Bill, Rank:5, Period:75
├ B-Rank
│ └ 87 days
│ └ Name:Dan, Rank:4, Period:87
├ C-Rank
│ └ 41 days
│ └ Name:Curt, Rank:3, Period:41
├ D-Rank
│ └ 32 days
│ ├ Name:Ada, Rank:2, Period:32
│ └ Name:Fleur, Rank:2, Period:32
└ E-Rank
└ 13 days
└ Name:Eden, Rank:1, Period:13
*/
// after use
ctgTreeView.Dispose();Objects that allow their property values to be observed implement INotifyPropertyChanged. This class is useful when you also want to monitor properties of values referenced by those properties, where those values themselves implement INotifyPropertyChanged.
public class ObservedPropertyTree<TSrc> : IDisposable{
public ObservedPropertyTree(TSrc source) { }
public PropertyChainNode Root {get;}
public void ChangeSource(TSrc target) { }
public IDisposable Subscribe(Expression<Func<TSrc, object>> expression, Action changedAction) { }
public IDisposable Subscribe<TValue>(Expression<Func<TSrc, TValue>> expression, Action<TValue> changedAction) { }
public IDisposable Subscribe<TValue>(Expression<Func<TSrc, TValue>> expression, EventHandler<ChainedPropertyChangedEventArgs<TValue>> changedAction) { }
public void Dispose(){ }
public class PropertyChainNode : TreeNodeBase<PropertyChainNode> {
public object Source { get; }
public string PropertyName { get; }
}
}
public class ChainedPropertyChangedEventArgs<T> : PropertyChangedEventArgs {
/// <summary>Constructor.</summary>
public ChainedPropertyChangedEventArgs(string? propertyName,IEnumerable<string> propertyChain, T propertyValue) { }
/// <summary>Changed property value</summary>
public T PropertyValue { get; }
/// <summary>Enumerates the names of the properties leading up to the changed property.</summary>
public IEnumerable<string> ChainedProperties { get; }
/// <summary>The full property path to the changed property, joined by dots.</summary>
public string ChainedName => string.Join(".", ChainedProperties);
}
Define the Onion class, which has a nested structure.
public class Onion : NotifyObjA {
public Onion Inside {
get => Properties.GetValue<Onion>();
set => Properties.TrySetValue(value);
}
public KnownColor SurfaceColor {
get => Properties.GetValue(KnownColor.White);
set => Properties.TrySetValue(value);
}
public override string ToString() {
return $"ColorOnion-{SurfaceColor.ToString()}";
}
}Build a nested structure and observe changes to the color at the third level.
var root = new KnownColor[] { KnownColor.Black, KnownColor.Brown, KnownColor.DarkKhaki, KnownColor.White }
.AssembleAsNAryTree(1,
clr => new Onion() { SurfaceColor = clr },
onion => onion.Inside is null ? Array.Empty<Onion>() : new Onion[] { onion.Inside },
(p, c) => { p.Inside = c; });
PrintHierarchy(root, x => new Onion[] { x.Inside }, x => x.SurfaceColor.ToString());
/*
└ Black
└ Brown
└ DarkKhaki
└ White
*/
var observingTree = new ObservedPropertyTree<Onion>(root);
var listner1 = observingTree.Subscribe(
x => x.Inside.Inside.SurfaceColor,
clr => Console.WriteLine($"3rd layer color changed: {clr}"));
root.Inside.Inside.SurfaceColor = KnownColor.Magenta;
//3rd layer color changed: Magenta
PrintHierarchy(root, x => new Onion[] { x.Inside }, x => x.SurfaceColor.ToString());
/*
└ Black
└ Brown
└ Magenta
└ White
*/
root.Inside = null;
//3rd layer color changed: 0
var redOnion = new KnownColor[] { KnownColor.Red, KnownColor.Green, KnownColor.LightPink }
.AssembleAsNAryTree(1,
clr => new Onion() { SurfaceColor = clr },
onion => onion.Inside is null ? Array.Empty<Onion>() : new Onion[] { onion.Inside },
(p, c) => { p.Inside = c; });
root.Inside = redOnion;
//3rd layer color changed: Green
PrintHierarchy(root, x => new Onion[] { x.Inside }, x => x.SurfaceColor.ToString());
/*
└ Black
└ Red
└ Green
└ LightPink
*/
var blueOnion = new KnownColor[] { KnownColor.Blue, KnownColor.Green, KnownColor.Gray }
.AssembleAsNAryTree(1,
clr => new Onion() { SurfaceColor = clr },
onion => onion.Inside is null ? Array.Empty<Onion>() : new Onion[] { onion.Inside },
(p, c) => { p.Inside = c; });
root.Inside = blueOnion;
//
PrintHierarchy(root, x => new Onion[] { x.Inside }, x => x.SurfaceColor.ToString());
/*
└ Black
└ Blue
└ Green
└ Gray
*/
root.Inside.Inside = redOnion;
//3rd layer color changed: Red
PrintHierarchy(root, x => new Onion[] { x.Inside }, x => x.SurfaceColor.ToString());
/*
└ Black
└ Blue
└ Red
└ Green
└ LightPink
*/Notifications are raised not only when the third-level SurfaceColor property is changed directly, but also when its value changes as a result of a change to an intermediate property.
If a null value is encountered along the property path and the final property cannot be reached, the default value is used.
You can also replace the source object dynamically.
var orangeOnion = new KnownColor[] { KnownColor.Orange, KnownColor.OrangeRed, KnownColor.DarkOrange }
.AssembleAsNAryTree(1,
clr => new Onion() { SurfaceColor = clr },
onion => onion.Inside is null ? Array.Empty<Onion>() : new Onion[] { onion.Inside },
(p, c) => { p.Inside = c; });
observingTree.ChangeSource(orangeOnion);
//3rd layer color changed: DarkOrangeAs an aside, ObservedPropertyTree is itself a tree structure. It stores the properties being monitored in a tree, as shown below.
Console.WriteLine(observingTree.Root.ToTreeDiagram(x => $"name:{x.PropertyName}, value:{x.Source.ToString()}"));
/*
name:, value:ColorOnion-Orange
└ name:Inside, value:ColorOnion-OrangeRed
└ name:Inside, value:ColorOnion-DarkOrange
└ name:SurfaceColor, value:DarkOrange
*/
//after use.
observingTree.Dispose();