質問するログイン新規登録

回答編集履歴

1

KeyedCollection について追記。

2019/03/14 16:02

投稿

imihito
imihito

スコア2166

answer CHANGED
@@ -1,4 +1,4 @@
1
- 既存のコレクションの中では、`System.Collections.Specialized.OrderedDictionary`が意図したものに近いと思われます。
1
+ 既存のコレクションの中では、`System.Collections.Specialized.OrderedDictionary`が意図したものに近いと思われます。
2
2
 
3
3
  > [OrderedDictionary Class (System.Collections.Specialized) | Microsoft Docs](https://docs.microsoft.com/ja-jp/dotnet/api/system.collections.specialized.ordereddictionary?redirectedfrom=MSDN&view=netframework-4.7.2)
4
4
 
@@ -78,7 +78,7 @@
78
78
  $dicN.Values
79
79
  <#
80
80
  1
81
- 4
81
+ 4 # 順番が変わる
82
82
  3
83
83
  #>
84
84
  ```
@@ -96,11 +96,64 @@
96
96
  <#
97
97
  1
98
98
  3
99
- 4
99
+ 4 # [2] の位置に追加される
100
100
  #>
101
101
  ```
102
102
 
103
103
 
104
104
  ## 参考記事
105
105
 
106
- > [PowerShellのHashtableの並び替えを制御したい - tech.guitarrapc.cóm](https://tech.guitarrapc.com/entry/2013/03/20/200351)
106
+ > [PowerShellのHashtableの並び替えを制御したい - tech.guitarrapc.cóm](https://tech.guitarrapc.com/entry/2013/03/20/200351)
107
+
108
+ ---
109
+
110
+ # 190315 追記 KeyedCollection 継承クラス
111
+
112
+ > [KeyedCollection<TKey,TItem> Class (System.Collections.ObjectModel) | Microsoft Docs](https://docs.microsoft.com/ja-jp/dotnet/api/system.collections.objectmodel.keyedcollection-2?view=netframework-4.7.2)
113
+
114
+ KeyedCollection を適当に継承したクラスを作ってみましたが、一応動いているようです(自分の環境ではインテリセンスが不安定なのがちょっと気になりますが)。
115
+
116
+ KeyedCollection は抽象クラスなので、継承した上で`GetKeyForItem`メソッドを実装して、各要素からキーを取得できるようする必要があります。
117
+ 今回はサンプルとして、コンストラクタに与えられたスクリプトブロックからキーを算出させるようにしています(設計としては色々怖いのであくまでサンプル)。
118
+
119
+ ```powershell
120
+ using namespace System.Collections.ObjectModel
121
+ using namespace System.Management.Automation
122
+
123
+ class MyKeyedList : KeyedCollection[string, PSCustomObject]
124
+ {
125
+ # must override method.
126
+ hidden [string]GetKeyForItem([PSCustomObject]$TItem) {
127
+ return [string](ForEach-Object -InputObject $TItem -Process $this._keySelector)
128
+ }
129
+ hidden [scriptblock]$_keySelector
130
+
131
+ MyKeyedList(
132
+ # $_ 自動変数を使ってキーを算出するScriptBlcokを指定する。
133
+ [scriptblock]$KeySelector
134
+ ) : base() {
135
+ $this._keySelector = $KeySelector
136
+ }
137
+ }
138
+
139
+ # Name プロパティをキーとする
140
+ $Dic = [MyKeyedList]::new({$_.Name})
141
+
142
+ $Ar = 0..9 |
143
+ %{
144
+ [PSCustomObject]@{
145
+ Name = "Name$_"
146
+ Text = "Text_$_"
147
+ Disp = "テキスト_$_"
148
+ }
149
+ }
150
+
151
+ $Ar |
152
+ %{
153
+ $Dic.Add($_)
154
+ }
155
+
156
+
157
+ Write-Host $Dic["Name5"].Name -ForegroundColor Red
158
+ Write-Host $Dic[5].Name -ForegroundColor Red
159
+ ```