やりたいこと
- あらかじめ限定しない任意の「キー」と「真偽値」のペアを扱いたい。
やってみたこと
- まず、単純に
Dictionary<TKey, TValue>
で実装しました。
var inventory = new Dictionary<string, bool> { };
var itemID = "檜の棒";
inventory [itemID] = Validate (itemID);
if (inventory.ContainsKey (itemID) && inventory [itemID]) {
// 持っている
}
- チェックが少々面倒です。
- キーの存在で所持を表せるのに、さらに真偽値を持つのはなんだか冗長です。
HashSet
で実装
- HashSetを拡張して、真偽値で制御するようにしました。
コード
BooleanHashSet.cs
using System.Collections.Generic;
public class BooleanHashSet<T> : HashSet<T> {
public bool this [T obj] {
get { return Contains (obj); }
set { if (value) { Add (obj); } else { Remove (obj); } }
}
}
使い方
var inventory = new BooleanHashSet<string> { };
var itemID = "檜の棒";
inventory [itemID] = Validate (itemID);
if (inventory [itemID]) {
// 持っている
}
改めてDictionary
で実装
- こちらの方法は、不要なデータを抱えていますが、HashSetより、ガベージは出にくそうだし、速度的にも有利っぽく見えます。(未検証)
BooleanDictionary.cs
using System.Collections.Generic;
public class BooleanDictionary<TKey> : Dictionary<TKey, bool> {
public new bool this [TKey key] {
get { return ContainsKey (key) && base [key]; }
set { base [key] = value; }
}
}
まとめ
- 「
Dictionary<TKey, bool>
で、何らかのキーと真偽値を扱うが、キーがない場合は偽としたい」という場合に使うのが、BooleanDictionary
です。 - あらかじめ、キーの総数あるいは内容が確定できず、逐次出現するような場合に使います。
- あらかじめ確定できる場合は、素の
Dictionary
が使えます。
- あらかじめ確定できる場合は、素の
- キーが次々と現れては消えるなど、「
Dictionary
だと、キー値ペアが蓄積されて不利益だ」という場合に使うのが、BooleanHashSet
です。- あるいは、単に、bool値を持つHashSetにインデクサでアクセスできるクラスです。