栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

获取通用字典的指定值的多个键?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

获取通用字典的指定值的多个键?

好的,这是多个双向版本:

using System;using System.Collections.Generic;using System.Text;class BiDictionary<TFirst, TSecond>{    IDictionary<TFirst, IList<TSecond>> firstToSecond = new Dictionary<TFirst, IList<TSecond>>();    IDictionary<TSecond, IList<TFirst>> secondToFirst = new Dictionary<TSecond, IList<TFirst>>();    private static IList<TFirst> EmptyFirstList = new TFirst[0];    private static IList<TSecond> EmptySecondList = new TSecond[0];    public void Add(TFirst first, TSecond second)    {        IList<TFirst> firsts;        IList<TSecond> seconds;        if (!firstToSecond.TryGetValue(first, out seconds))        { seconds = new List<TSecond>(); firstToSecond[first] = seconds;        }        if (!secondToFirst.TryGetValue(second, out firsts))        { firsts = new List<TFirst>(); secondToFirst[second] = firsts;        }        seconds.Add(second);        firsts.Add(first);    }    // Note potential ambiguity using indexers (e.g. mapping from int to int)    // Hence the methods as well...    public IList<TSecond> this[TFirst first]    {        get { return GetByFirst(first); }    }    public IList<TFirst> this[TSecond second]    {        get { return GetBySecond(second); }    }    public IList<TSecond> GetByFirst(TFirst first)    {        IList<TSecond> list;        if (!firstToSecond.TryGetValue(first, out list))        { return EmptySecondList;        }        return new List<TSecond>(list); // Create a copy for sanity    }    public IList<TFirst> GetBySecond(TSecond second)    {        IList<TFirst> list;        if (!secondToFirst.TryGetValue(second, out list))        { return EmptyFirstList;        }        return new List<TFirst>(list); // Create a copy for sanity    }}class Test{    static void Main()    {        BiDictionary<int, string> greek = new BiDictionary<int, string>();        greek.Add(1, "Alpha");        greek.Add(2, "Beta");        greek.Add(5, "Beta");        ShowEntries(greek, "Alpha");        ShowEntries(greek, "Beta");        ShowEntries(greek, "Gamma");    }    static void ShowEntries(BiDictionary<int, string> dict, string key)    {        IList<int> values = dict[key];        StringBuilder builder = new StringBuilder();        foreach (int value in values)        { if (builder.Length != 0) {     builder.Append(", "); } builder.Append(value);        }        Console.WriteLine("{0}: [{1}]", key, builder);    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/395420.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号