4 回答

TA貢獻(xiàn)1796條經(jīng)驗 獲得超4個贊
請不要這樣做。字典針對一鍵到一值搜索進(jìn)行了優(yōu)化。
我對單個值使用多個鍵的建議如下:
private Dictionary<string, ICommand> commandsWithAttributes = new Dictionary<string, ICommand>();
var command1 = new Command(); //Whatever
commandsWithAttributes.Add("-t", command1);
commandsWithAttributes.Add("--thread", command1);
var command2 = new Command(); //Whatever
commandsWithAttributes.Add("-?", command2);
commandsWithAttributes.Add("--help", command2);

TA貢獻(xiàn)1799條經(jīng)驗 獲得超8個贊
這對{"-t","--thread"}
稱為命令行選項。-t
是選項的短名稱,--thread
是其長名稱。當(dāng)您查詢字典以通過部分鍵獲取條目時,您實際上希望它由短名稱索引。我們假設(shè):
所有選項都有短名稱
所有選項都是字符串?dāng)?shù)組
短名稱是字符串?dāng)?shù)組中的第一項
然后我們可以有這個比較器:
public class ShortNameOptionComparer : IEqualityComparer<string[]>
{
public bool Equals(string[] x, string[] y)
{
return string.Equals(x[0], y[0], StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(string[] obj)
{
return obj[0].GetHashCode();
}
}
...并將其插入字典中:
private Dictionary<string[], ICommand> commandsWithAttributes = new Dictionary<string[], ICommand>(new ShortNameOptionComparer());
要查找命令,我們必須使用string[]僅包含短名稱的命令,即-t: var value = dictionary[new [] { "-t" }]。或者將其包裝在擴(kuò)展方法中:
public static class CompositeKeyDictionaryExtensions
{
public static T GetValueByPartialKey<T>(this IDictionary<string[], T> dictionary, string partialKey)
{
return dictionary[new[] { partialKey }];
}
}
...并用它來獲取值:
var value = dictionary.GetValueByPartialKey("-t");

TA貢獻(xiàn)1821條經(jīng)驗 獲得超6個贊
您可以通過迭代所有鍵來搜索
var needle = "-?";
var kvp = commandsWithAttributes.Where(x => x.Key.Any(keyPart => keyPart == needle)).FirstOrDefault();
Console.WriteLine(kvp.Value);
但它不會給你使用字典帶來任何優(yōu)勢,因為你需要迭代所有的鍵。最好先扁平化你的層次結(jié)構(gòu)并搜索特定的鍵
var goodDict = commandsWithAttributes
.SelectMany(kvp =>
kvp.Key.Select(key => new { key, kvp.Value }))
.ToDictionary(x => x.key, x => x.Value);
Console.WriteLine(goodDict["-?"]);

TA貢獻(xiàn)1833條經(jīng)驗 獲得超4個贊
private Dictionary<string[], ICommand> commandsWithAttributes = new Dictionary<string[], ICommand>();
private ICommand FindByKey(string key)
{
foreach (var p in commandsWithAttributes)
{
if (p.Key.Any(k => k.Equals(key)))
{
return p.Value;
}
}
return null;
}
并調(diào)用像
ICommand ic = FindByKey("-?");
- 4 回答
- 0 關(guān)注
- 249 瀏覽
添加回答
舉報