きゅぶろぐ

きゅぶんずの ぶろぐができて べんりだな

C#でKey-Valueどちらからどちらでも引ける双方向マップbimap

よく使うので作りました。

使い方

var bimap = new Bimap<int, string>();

bimap[110] = "警察";
bimap[119] = "消防";

Console.WriteLine(bimap[110]); // 警察
Console.WriteLine(bimap["消防"]); // 119

bimap["災害用伝言ダイヤル"] = 171;
bimap["天気予報"] = 177;

Console.WriteLine(bimap[171]); // 災害用伝言ダイヤル
Console.WriteLine(bimap["天気予報"]); // 177

コード

/*
Bimap

MIT License

Copyright (c) 2021 kyubuns

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

public interface IReadonlyBimap<TL, TR>
{
    int Count { get; }
    TR this[TL key] { get; }
    TL this[TR key] { get; }
    bool ContainsKey(TL key);
    bool ContainsKey(TR key);
    bool TryGetValue(TL key, out TR value);
    bool TryGetValue(TR key, out TL value);
    IEnumerable<TL> LeftKeys { get; }
    IEnumerable<TR> RightKeys { get; }
    IReadOnlyDictionary<TL, TR> Left { get; }
    IReadOnlyDictionary<TR, TL> Right { get; }
}

public class Bimap<TL, TR> : IReadonlyBimap<TL, TR>
{
    public int Count => _left.Count;

    public TR this[TL key]
    {
        get => _left[key];
        set
        {
            _left[key] = value;
            _right[value] = key;
        }
    }

    public TL this[TR key]
    {
        get => _right[key];
        set
        {
            _right[key] = value;
            _left[value] = key;
        }
    }

    public IEnumerable<TL> LeftKeys => _left.Keys;
    public IEnumerable<TR> RightKeys => _right.Keys;
    public bool ContainsKey(TL key) => _left.ContainsKey(key);
    public bool ContainsKey(TR key) => _right.ContainsKey(key);
    public bool TryGetValue(TL key, out TR value) => _left.TryGetValue(key, out value);
    public bool TryGetValue(TR key, out TL value) => _right.TryGetValue(key, out value);

    public IReadOnlyDictionary<TL, TR> Left => _left;
    public IReadOnlyDictionary<TR, TL> Right => _right;

    private readonly Dictionary<TL, TR> _left;
    private readonly Dictionary<TR, TL> _right;

    public Bimap()
    {
        _left = new Dictionary<TL, TR>();
        _right = new Dictionary<TR, TL>();
    }

    public Bimap(int capacity)
    {
        _left = new Dictionary<TL, TR>(capacity);
        _right = new Dictionary<TR, TL>(capacity);
    }

    public Bimap(IEnumerable<KeyValuePair<TL, TR>> source)
    {
        _left = new Dictionary<TL, TR>();
        _right = new Dictionary<TR, TL>();

        foreach (var keyValuePair in source) Add(keyValuePair.Key, keyValuePair.Value);
    }

    public void Add(TL left, TR right)
    {
        if (_left.ContainsKey(left)) throw new ArgumentException(nameof(left));
        if (_right.ContainsKey(right)) throw new ArgumentException(nameof(right));
        _left.Add(left, right);
        _right.Add(right, left);
    }

    public void Add(TR right, TL left)
    {
        if (_right.ContainsKey(right)) throw new ArgumentException(nameof(right));
        if (_left.ContainsKey(left)) throw new ArgumentException(nameof(left));
        _right.Add(right, left);
        _left.Add(left, right);
    }

    public bool Remove(TR right)
    {
        if (!_right.TryGetValue(right, out var left)) return false;
        _right.Remove(right);
        _left.Remove(left);
        return true;
    }

    public bool Remove(TL left)
    {
        if (!_left.TryGetValue(left, out var right)) return false;
        _left.Remove(left);
        _right.Remove(right);
        return true;
    }

    public void Clear()
    {
        _left.Clear();
        _right.Clear();
    }
}

public static class BimapExtensions
{
    public static Bimap<TL, TR> ToBimap<TL, TR>(this IEnumerable<KeyValuePair<TL, TR>> source)
    {
        return new Bimap<TL, TR>(source);
    }
}

あとがき

「え、これintとintでは使えなくない?」と思った方、鋭いですね。
それぞれ別の型を入れたときのinterfaceをいい感じにしたかったので諦めました。

パフォーマンス重視のために、Addするときにコピーしてるので、Getして書き換えられたりすると死にます。