按键c#字典的一部分获取值
我有这本字典按键c#字典的一部分获取值,c#,dictionary,C#,Dictionary,我有这本字典 private Dictionary<string[], ICommand> commandsWithAttributes = new Dictionary<string[], ICommand>(); private Dictionary命令swithattributes=new Dictionary(); 我需要在命令中按部分键查找属性为的元素。我的意思是: “-?”-是我用来查找项目的键 ({“-t”,“--thread”},ICommand) (
private Dictionary<string[], ICommand> commandsWithAttributes = new Dictionary<string[], ICommand>();
private Dictionary命令swithattributes=new Dictionary();
我需要在命令中按部分键查找属性为的元素。我的意思是:
“-?”
-是我用来查找项目的键
({“-t”,“--thread”},ICommand)
({“-?”,“--help”},ICommand)
您可以通过迭代所有键进行搜索
var needle = "-?";
var kvp = commandsWithAttributes.Where(x => x.Key.Any(keyPart => keyPart == needle)).FirstOrDefault();
Console.WriteLine(kvp.Value);
但是使用Dictionary不会给您带来任何好处,因为您需要迭代所有键。最好先将层次结构展平,然后搜索特定的键
var goodDict = commandsWithAttributes
.SelectMany(kvp =>
kvp.Key.Select(key => new { key, kvp.Value }))
.ToDictionary(x => x.key, x => x.Value);
Console.WriteLine(goodDict["-?"]);
请不要这样做。字典针对一键对一值搜索进行了优化
我建议对单个值使用多个键,如下所示:
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);
private Dictionary命令swithattributes=new Dictionary();
var command1=新命令()//无论什么
添加(“-t”,command1);
添加(“--thread”,command1);
var command2=新命令()//无论什么
命令属性。添加(“-?”,命令2);
添加(“--help”,command2);
这对{“-t”,“--thread”}
称为命令行选项-t
是选项的短名称,--thread
是选项的长名称。当您查询字典以通过部分键获取条目时,实际上您希望通过短名称对其进行索引。让我们假设:
- 所有选项都有短名称
- 所有选项都是字符串数组
- 短名称是字符串数组中的第一项
然后我们可以使用这个比较器:
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();
}
}
。。。并使用它来获取值:
var value = dictionary.GetValueByPartialKey("-t");
如果多个键具有您正在搜索的字符串,该怎么办?@Sweeper此键是唯一的。如果我需要搜索{“-?”,“--help”}-我可以使用“-?”来查找这看起来像命令行解析。为什么不使用内置此功能的现有命令行解析器库?@Suiden I研究。
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());
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");