LoginSignup
0
0

More than 3 years have passed since last update.

含有を真偽で扱うHashSet / Dictionary (C#)

Last updated at Posted at 2019-08-06

やりたいこと

  • あらかじめ限定しない任意の「キー」と「真偽値」のペアを扱いたい。

やってみたこと

  • まず、単純に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にインデクサでアクセスできるクラスです。
0
0
16

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0