【问题标题】:How to create a Lookup<string, delegate> collection如何创建一个 Lookup<string, delegate> 集合
【发布时间】:2015-12-14 10:05:13
【问题描述】:

我需要能够根据键过滤集合中的一组委托。每个密钥将有一个或多个与之关联的委托。看起来Lookup&lt;TKey, TElement&gt; 可以在这里提供帮助,但我不确定是否可以创建一个TKey 不是从TElement 的属性派生的(在我的情况下,TElement 将是一个代表类型并且不会知道任何关于标识符的信息)。

更新

例如,如果我使用Dictionary,我可能会像下面的示例那样索引和过滤我的代表列表:

private delegate MyMethod MethodName(string key);

IDictionary<string, MyMethod> methodList = new Dictionary<string, MyMethod>();
methodList.Add("Key1", Method1);
methodList.Add("Key1", Method2);
methodList.Add("Key2", Method3);
methodList.Add("Key3", Method4);
methodList.Add("Key3", Method5);

var someMethods = methodlist["Key3"];

但是,这会失败,因为 Dictionary 需要唯一的密钥,在我的场景中,每个密钥有多个条目。 Lookup 支持每个键的多个条目,但无法使用 Add 方法实例化它。我正在寻找一种实例化 Lookup 的方法,以便使用任意键对代表列表进行索引。

请问有人可以建议一种方法吗?

【问题讨论】:

  • 很难理解你在问什么。你能说得更清楚一点吗?也许有一些代码示例?
  • 在上面添加了一些示例代码和更多讨论。
  • 你可以改用Dictionary&lt;string, List&lt;MyMethod&gt;&gt;
  • 降价是为了什么?
  • @SriramSakthivel,谢谢,但我正在寻找基于 Lookup 的解决方案,因为我想学习如何使用它。

标签: .net collections delegates


【解决方案1】:

我通过将委托包装在一个还包含密钥的类中找到了解决方案:

private delegate MyMethod DoStuff();

private class MethodWrapper
{
    public MethodWrapper(string key, MyMethod method)
    {
        Key = key;
        Method = method;
    }
    public string Key { get; private set; }
    public MyMethod Method { get; private set; }
}

然后您可以生成这样的查找:

private static IEnumerable<GetChart> GetMethodList(string key)
{
    IEnumerable<MethodWrapper> methods = new List<MethodWrapper>()
    {
        new MethodWrapper("Key1", Method1),
        new MethodWrapper("Key2", Method2),
        new MethodWrapper("Key2", Method3)
    };
    ILookup<string, GetChart> lookup = methods.ToLookup(m => m.Key, m => m.Method);

    return lookup[key];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多