通过C#字典的键的一部分获取值

我有这本词典。

private Dictionary<string[], ICommand> commandsWithAttributes = new Dictionary<string[], ICommand>();

我需要commandsWithAttributes通过部分键来查找元素。我的意思是说:

"-?"- 是我用来查找物品的钥匙。

({"-t","--thread"},ICommand)

({"-?","--help"},ICommand)<- 这就是我需要找到的。


手掌心
浏览 194回答 4
4回答

SMILET

请不要这样做。字典针对一键到一值搜索进行了优化。我对单个值使用多个键的建议如下:private Dictionary<string, ICommand> commandsWithAttributes = new Dictionary<string, ICommand>();var command1 = new Command(); //WhatevercommandsWithAttributes.Add("-t", command1);commandsWithAttributes.Add("--thread", command1);var command2 = new Command(); //WhatevercommandsWithAttributes.Add("-?", command2);commandsWithAttributes.Add("--help", command2);

守着星空守着你

这对{"-t","--thread"}称为命令行选项。-t是选项的短名称,--thread是其长名称。当您查询字典以通过部分键获取条目时,您实际上希望它由短名称索引。我们假设:所有选项都有短名称所有选项都是字符串数组短名称是字符串数组中的第一项然后我们可以有这个比较器:public class ShortNameOptionComparer : IEqualityComparer<string[]>{&nbsp; &nbsp; public bool Equals(string[] x, string[] y)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return string.Equals(x[0], y[0], StringComparison.OrdinalIgnoreCase);&nbsp; &nbsp; }&nbsp; &nbsp; public int GetHashCode(string[] obj)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return obj[0].GetHashCode();&nbsp; &nbsp; }}...并将其插入字典中:private Dictionary<string[], ICommand> commandsWithAttributes = new Dictionary<string[], ICommand>(new ShortNameOptionComparer());要查找命令,我们必须使用string[]仅包含短名称的命令,即-t: var value = dictionary[new [] { "-t" }]。或者将其包装在扩展方法中:public static class CompositeKeyDictionaryExtensions{&nbsp; &nbsp; public static T GetValueByPartialKey<T>(this IDictionary<string[], T> dictionary, string partialKey)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return dictionary[new[] { partialKey }];&nbsp; &nbsp; }}...并用它来获取值:var value = dictionary.GetValueByPartialKey("-t");

达令说

您可以通过迭代所有键来搜索var needle = "-?";var kvp = commandsWithAttributes.Where(x => x.Key.Any(keyPart => keyPart == needle)).FirstOrDefault();Console.WriteLine(kvp.Value);但它不会给你使用字典带来任何优势,因为你需要迭代所有的键。最好先扁平化你的层次结构并搜索特定的键var goodDict = commandsWithAttributes&nbsp; &nbsp; .SelectMany(kvp =>&nbsp; &nbsp; &nbsp; &nbsp; kvp.Key.Select(key => new { key, kvp.Value }))&nbsp; &nbsp; .ToDictionary(x => x.key, x => x.Value);Console.WriteLine(goodDict["-?"]);

潇潇雨雨

private Dictionary<string[], ICommand> commandsWithAttributes = new Dictionary<string[], ICommand>();private ICommand FindByKey(string key)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; foreach (var p in commandsWithAttributes)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (p.Key.Any(k => k.Equals(key)))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return p.Value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }并调用像ICommand ic = FindByKey("-?");
打开App,查看更多内容
随时随地看视频慕课网APP