Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return key value pair from a function

I am implementing a function in C#. This is the function in my class.I need to get the values from the function to the form.

    public void GetRoles(string strGetRoles)
    {
        string keyObj;
        string valueObj;
        var parseTree = JsonConvert.DeserializeObject<JObject>(strGetRoles);

        foreach (var prop in parseTree.Properties())
        {
            dynamic propValue = prop.Value;
            if (prop.Name == "roles" && prop.Value.HasValues)
            {
                foreach (var proval in propValue)
                {
                    keyObj = (string)proval.Name;
                    valueObj = (string)proval.Value;                                               
                }
            }
            else if (prop.Name == "groups" && prop.Value.HasValues)
            {
                foreach (var proval in propValue)
                {
                    keyObj = (string)proval.Name;
                    valueObj = (string)proval.Value;
                }
            }
        }
 }

strGetRoles is the response string I get after fetching json api. the propvalue I get is {"roles": {"3": "Reseller","2": "Admin end user"},"groups": []}

Now I want to call this function and get each value in an object or string array.How to return these key pair values? Thanks in advance!

like image 638
abi Avatar asked Dec 23 '13 07:12

abi


2 Answers

You can return KeyValuePair like this:

return new KeyValuePair<string,string>(key,value);

or use Tuple

return Tuple.Create(key,value);

if you have more than one KeyValuePair to return use Dictionary, you can read more about performance differences between Tuple and KeyValuePair here. In short using Tuple is better idea because of it's better performance.

like image 167
Kamil Budziewski Avatar answered Oct 20 '22 19:10

Kamil Budziewski


Use Tuple<T1, T2>.

public Tuple<string, string> GetRoles(string strGetRoles)
{
    //...
    return Tuple.Create(key, value);
}

If you have more than one key-value pair, then return a Dictionary<string, string> instead.

like image 43
dcastro Avatar answered Oct 20 '22 19:10

dcastro