Returning two dictionaries with Tuple from one method within another class

 ̄綄美尐妖づ 提交于 2019-12-25 08:58:34

问题


I have one class, class AClass. In this class I'm filling two dictionaries and also, I'm returning these two dictionaries so I've used Tuple<Dictionary<string, string>, Dictionary<string, string>> type of method declaration:

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

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

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

In other class, class BClass, I should get these two dictionaries, access them and add their items to another two dictionaries:

 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 should get dictionaries through Tuple
    //Add items from dictOne to dictThree
    //Add items from dictTwo to dictFour
    //In a way
    //   foreach (var v in accessedDict)
    //   {
    //   dictThree.Add(v.Key, v.Value);
    //   }
    }
}

If MyMethodOne was returning only one dictionary I would know how to get items from one dictionary to another but here I have Tuple, with which I have never worked, and I don't know how how to get these two retuning values. Should I do it like this at all? Is there another way, maybe to declare method as Dictionary< Dictionary<string, string>, Dictionary<string, string>>?

So, how to get dictionaries from Tuple?


回答1:


The Tuple class exposes its members in properties called "Item(Number)": http://msdn.microsoft.com/en-us/library/dd289533.aspx

So, your two-items Tuple will have properties called Item1 and Item2:

var dictionaries = _ac.MyMethodOne();
// now dictionaries.Item1 = dictOne, dictionaries,Item2 = dictTwo
dictThree = dictionaries.Item1;

I don't understand when you say that you want to "assign items" if you just want to get a reference to the dictionary or make a copy of it. If you want to make a copy, use

dictFour = new Dictionary<string, string>(dictionaries.Item2);


来源:https://stackoverflow.com/questions/13705852/returning-two-dictionaries-with-tuple-from-one-method-within-another-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!