为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
手掌心 2023-08-13 13:59:44
我有这本词典。private Dictionary<string[], ICommand> commandsWithAttributes = new Dictionary<string[], ICommand>();我需要commandsWithAttributes通过部分键来查找元素。我的意思是说:"-?"- 是我用来查找物品的钥匙。({"-t","--thread"},ICommand)({"-?","--help"},ICommand)<- 这就是我需要找到的。
查看完整描述

4 回答

?
SMILET

TA贡献1796条经验 获得超4个赞

请不要这样做。字典针对一键到一值搜索进行了优化。


我对单个值使用多个键的建议如下:


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);


查看完整回答
反对 回复 2023-08-13
?
守着星空守着你

TA贡献1799条经验 获得超8个赞

这对{"-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();

    }

}

...并将其插入字典中:


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

要查找命令,我们必须使用string[]仅包含短名称的命令,即-t: var value = dictionary[new [] { "-t" }]。或者将其包装在扩展方法中:


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");


查看完整回答
反对 回复 2023-08-13
?
达令说

TA贡献1821条经验 获得超6个赞

您可以通过迭代所有键来搜索


var needle = "-?";

var kvp = commandsWithAttributes.Where(x => x.Key.Any(keyPart => keyPart == needle)).FirstOrDefault();

Console.WriteLine(kvp.Value);

但它不会给你使用字典带来任何优势,因为你需要迭代所有的键。最好先扁平化你的层次结构并搜索特定的键


var goodDict = commandsWithAttributes

    .SelectMany(kvp =>

        kvp.Key.Select(key => new { key, kvp.Value }))

    .ToDictionary(x => x.key, x => x.Value);


Console.WriteLine(goodDict["-?"]);


查看完整回答
反对 回复 2023-08-13
?
潇潇雨雨

TA贡献1833条经验 获得超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;

    }

并调用像


ICommand ic = FindByKey("-?");


查看完整回答
反对 回复 2023-08-13
  • 4 回答
  • 0 关注
  • 113 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信