【问题标题】:c# explode tuple into dictionary entry [duplicate]c#将元组分解成字典条目[重复]
【发布时间】:2021-05-22 17:02:48
【问题描述】:

您好,我有一个返回 2 个值的元组的函数,我想将它们放入一行添加中,如下所示:

Dictionary<string, string> test = new Dictionary<string, string>();
test.Add(intoDict());

private (string, string) intoDict()
{
    return ("Key","Value");
}

我需要这是一个单行操作。

【问题讨论】:

  • 到目前为止你有没有尝试过?您在实施过程中遇到了哪些问题。
  • 我尝试了上面的代码,但它不起作用,因为它被视为一个值,而不是 2,除此之外,我不知道如何在不创建更多不必要代码的情况下解决它。我需要多次调用这个函数,所以我想保持它干净

标签: c#


【解决方案1】:

如果出于某种原因它必须是一个单行器,您可以创建一个扩展方法来处理元组值:

    public static class Extension
    {
        public static void Add<TKey, TValue>(this IDictionary<TKey, TValue> dic, ValueTuple<TKey, TValue> tuple)
        {
            dic[tuple.Item1] = tuple.Item2;
        }
    }

然后可以这样调用:

static (string, string) intoDict()
{
    return ("Key", "Value");
}

static void Main(string[] args)
{
    Dictionary<string, string> dic = new Dictionary<string, string>();
    dic.Add(intoDict()); //added here
    return;
}

【讨论】:

    【解决方案2】:

    您需要在Add 方法中分别指定 keyvalue,如下所示,因为它需要两个参数,第一个键和第二个值:

    var tupleResult = intoDict();
    test.Add(tupleResult.Item1, tupleResult.Item2);
    

    【讨论】:

    • 这种方式确实有效,但这不是一个单行程序,并且会创建比我已经创建的更多的代码......所以我正在尝试寻找一种干净的方式来做到这一点。
    • @RobinDeWolf 您可能使用了错误的“干净”定义。
    • 首先有一个像intoDict 这样的方法看起来并不干净,它返回一个你不需要的静态元组。为什么不提供构建字典的方法?
    • @TimSchmelter 当然,有多种方法可以完成这项工作,如果我们真的想要一个班轮,可以通过扩展方法发布杰克
    【解决方案3】:

    考虑使用extension method.

    public static class DictionaryExtensions
    {
        public static void Add<T, U>(this IDictionary<T, U> Dictionary, (T, U) tuple)
        {
            Dictionary.TryAdd(tuple.Item1, tuple.Item2);
        }
    }
    

    此扩展方法为任何IDictionary 提供.Add()

    要使用它,只需这样做:

    (string,string) myTuple = ( "Key", "Value");
    
    dictionary.Add(myTuple);
    

    【讨论】:

      猜你喜欢
      • 2013-09-11
      • 2021-11-06
      • 2012-05-20
      • 2015-10-04
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      相关资源
      最近更新 更多