Skip to content

Tutorial7.ja

houzkin edited this page Nov 9, 2026 · 4 revisions

定義済みTree

CategoryTree

追加された要素をツリー状にカテゴリー分けをします。

CategoryTree.cs

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; }
    }
}

UML7

次のコードで、追加されたDateTimeを年/月/日ごとにツリー状に分類します。

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
*/

追加された要素に伴って、カテゴリーノードも生成されています。
各カテゴリーをソートするため、以下のラッパーを使用します。

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;
}

上記と同様の処理を行い、ソートされたラッパーを表示します。

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
*/

ReactiveCategoryTree

指定したプロパティを監視し、その変更によって再分類します。
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>を定義しています。
これにより、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
);

次のコードで、Playerクラスと、NodeクラスのラッパーとなるPlayerViewクラスを定義します。

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;
}

上記クラスを使用してカテゴリー分けを行い、プロパティを変更してみます。

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();

ObservedPropertyTree

プロパティ値の変更を観測できるオブジェクトはINotifyPropertyChangedを実装しますが、更にそのプロパティが示す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);
}

UML6

入れ子構造となるOnionクラスを定義します。

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()}";
	}
}

入れ子構造を組立てて、3層目の色の変化を観測します。

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
*/

3層目のSurfaceColorプロパティが直接変更さた時だけでなく、経由するプロパティ値が変更された結果ことによって変化した場合も、通知を受け取ることができます。
経由途中にnullがあり辿り着けなかった場合はデフォルト値となります。

また、動的にソースオブジェクトを差し替えることもできます。

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: DarkOrange

余談になりますがObservedPropertyTreeもツリー構造をなしています。以下のように監視しているプロパティをツリー構造で保持しています。

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();

Clone this wiki locally