返回两个词典的方法

时间:2012-12-05 09:03:16

标签: c# dictionary

我试图返回两个字典并成功但我对它不满意因为它很慢。以下是我迄今为止使用Tupla所做的事情:Returning two dictionaries with Tuple from one method within another class

这也是基准,支持我的说法,即Tupla很慢:http://www.dotnetperls.com/multiple-return-values

Returning two dictionaries with Tuple from one method within another class考虑​​相同的情况我尝试使用KeyValuePair声明代替Tupla,但我收到此错误:

  

无法隐式转换类型   'System.Tuple,System.Collections.Generic.Dictionary>'   至   'System.Collections.Generic.KeyValuePair,System.Collections.Generic.Dictionary>'

以下是代码:

class AClass
{
    Dictionary<string, string> dictOne = new Dictionary<string, string>();
    Dictionary<string, string> dictTwo = new Dictionary<string, string>();

    public KeyValuePair<Dictionary<string, string>, Dictionary<string, string>> MyMethodOne()
    {
        //Adding items dictOne and dictTwo

        return new KeyValuePair<Dictionary<string, string>, Dictionary<string, string>>(dictOne, dictTwo);
    }
}

class BClass 
{
        AClass _ac = new AClass();

        Dictionary<string, string> dictThree = new Dictionary<string, string>();
        Dictionary<string, string> dictFour = new Dictionary<string, string>();

        public void MyMethodTwo()
        {
         //Here I get mentioned error
         KeyValuePair<Dictionary<string, string>, Dictionary<string, string>> calledKVP = _ac.MyMethodOne();

         Dictionary<string, string> dictThree = calledKVP.Key;
         Dictionary<string, string> dictFour = calledKVP.Value;
         //After this I loop through dictThree and dictFour and do what I need
        }
    }

我担心这意味着“Tupla方式”无法以其他方式完成。

有什么建议吗?

1 个答案:

答案 0 :(得分:4)

首先,您可以使用Tuple

public Tuple<Dictionary<T1, T2>, Dictionary<T1, T2>> GetDictionaries<T1, T2>()
{
    var dict1 = new Dictionary<T1, T2>();
    var dict2 = new Dictionary<T1, T2>();
    return Tuple.Create(dict1, dict2);
}

public void Method()
{
    var result = GetDictionaries(int, string);
    var dict1 = result.Item1;
    var dict2 = result.Item2;
}

另一个具有多个输出参数的解决方案是使用out参数

public void SetDictionaries(
    out Dictionary<int, string> dict1, out dictionary<int, double> dict2)
{

    dict1 = new Dictionary<int, string);
    dict2 = new Dictionary<int, double);

}

public void Method()
{
    Dictionary<int, string) dict1;
    Dictionary<int, double) dict2;

    SetDictionaries(out dict1, out dict2);
}

使用KeyValuePair

public KeyValuePair<Dictionary<int, int>, Dictionary<string, string>> GetDictionaries()
{
    var dict1 = new Dictionary<int, int>();
    var dict2 = new Dictionary<string, string>();

    return new KeyValuePair<Dictionary<int, int>, Dictionary<string, string>>(dict1, dict2);
}


public void Method()
{
    var result = GetDictionaries();
    var dict1 = result.Key;
    var dict2 = result.Value;
}