回答編集履歴

1

KeyedCollection について追記。

2019/03/14 16:02

投稿

imihito
imihito

スコア2166

test CHANGED
@@ -1,4 +1,4 @@
1
- 既存のコレクションの中では、`System.Collections.Specialized.OrderedDictionary`が意図したものに近いと思われます。
1
+ 既存のコレクションの中では、`System.Collections.Specialized.OrderedDictionary`が意図したものに近いと思われます。
2
2
 
3
3
 
4
4
 
@@ -158,7 +158,7 @@
158
158
 
159
159
  1
160
160
 
161
- 4
161
+ 4 # 順番が変わる
162
162
 
163
163
  3
164
164
 
@@ -194,7 +194,7 @@
194
194
 
195
195
  3
196
196
 
197
- 4
197
+ 4 # [2] の位置に追加される
198
198
 
199
199
  #>
200
200
 
@@ -209,3 +209,109 @@
209
209
 
210
210
 
211
211
  > [PowerShellのHashtableの並び替えを制御したい - tech.guitarrapc.cóm](https://tech.guitarrapc.com/entry/2013/03/20/200351)
212
+
213
+
214
+
215
+ ---
216
+
217
+
218
+
219
+ # 190315 追記 KeyedCollection 継承クラス
220
+
221
+
222
+
223
+ > [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)
224
+
225
+
226
+
227
+ KeyedCollection を適当に継承したクラスを作ってみましたが、一応動いているようです(自分の環境ではインテリセンスが不安定なのがちょっと気になりますが)。
228
+
229
+
230
+
231
+ KeyedCollection は抽象クラスなので、継承した上で`GetKeyForItem`メソッドを実装して、各要素からキーを取得できるようする必要があります。
232
+
233
+ 今回はサンプルとして、コンストラクタに与えられたスクリプトブロックからキーを算出させるようにしています(設計としては色々怖いのであくまでサンプル)。
234
+
235
+
236
+
237
+ ```powershell
238
+
239
+ using namespace System.Collections.ObjectModel
240
+
241
+ using namespace System.Management.Automation
242
+
243
+
244
+
245
+ class MyKeyedList : KeyedCollection[string, PSCustomObject]
246
+
247
+ {
248
+
249
+ # must override method.
250
+
251
+ hidden [string]GetKeyForItem([PSCustomObject]$TItem) {
252
+
253
+ return [string](ForEach-Object -InputObject $TItem -Process $this._keySelector)
254
+
255
+ }
256
+
257
+ hidden [scriptblock]$_keySelector
258
+
259
+
260
+
261
+ MyKeyedList(
262
+
263
+ # $_ 自動変数を使ってキーを算出するScriptBlcokを指定する。
264
+
265
+ [scriptblock]$KeySelector
266
+
267
+ ) : base() {
268
+
269
+ $this._keySelector = $KeySelector
270
+
271
+ }
272
+
273
+ }
274
+
275
+
276
+
277
+ # Name プロパティをキーとする
278
+
279
+ $Dic = [MyKeyedList]::new({$_.Name})
280
+
281
+
282
+
283
+ $Ar = 0..9 |
284
+
285
+ %{
286
+
287
+ [PSCustomObject]@{
288
+
289
+ Name = "Name$_"
290
+
291
+ Text = "Text_$_"
292
+
293
+ Disp = "テキスト_$_"
294
+
295
+ }
296
+
297
+ }
298
+
299
+
300
+
301
+ $Ar |
302
+
303
+ %{
304
+
305
+ $Dic.Add($_)
306
+
307
+ }
308
+
309
+
310
+
311
+
312
+
313
+ Write-Host $Dic["Name5"].Name -ForegroundColor Red
314
+
315
+ Write-Host $Dic[5].Name -ForegroundColor Red
316
+
317
+ ```