简体   繁体   中英

How to add values into a variable of type object in C#

Now I'am this is what actual code looks like, which is debugging(running) successfully:

object attributes = new object[] { 
                  "key1=value1",
                  "key2=value2",
                  "key3=value3",
                  "key4=value4",
                  "keyN=valueN" 
};

I need to change the values sometimes, so I am using C# Dictionary which is defined as:

public Dictionary<string,string> dAttributes=new Dictionary<string,string>();

I am adding the KEY and VALUE in the dictionary one by one. But when I try to typecast(which I think is not possible) or apply any other logic, the values in the object named "attributes" are not getting in proper format.

First I tried this:

object attributes = new object[]{dAttributes};

Then I did this:

            int i=0;
            string attribueKeyAndValues;
            attribueKeyAndValues = "";
            foreach (KeyValuePair<string,string> item in dAttributes)
            {
                if(i==(dealAttributes.Count-1))
                    attribueKeyAndValues+="\"" +item.Key+"="+item.Value+"\"";
                else
                    attribueKeyAndValues += "\"" + item.Key +"="+ item.Value + "\"" + ",";
                i++;
            }

            attributes = new object[] { attribueKeyAndValues };

Now this code is not working because attribute is taking the entire string as a single value. Plus more important thing is when I debug the code and quick watch the value in attribueKeyAndValues (in Text Visualizer) is shows me "\\key=value\\","\\key=value\\" and so on.

Is there any other way to add the values in the attribute ?

conversion from dictionary to array

attributes = dAttributes.Select(a=>a.Key+"="+a.Value).ToArray();

here a co-variant array conversion is used ( ToArray() returns string[] , but it can be assigned to object[] variable)

but if you really need object[] , make a cast

attributes = dAttributes.Select(a=>(object)(a.Key+"="+a.Value)).ToArray();

then something like attributes[0] = 1; will work (in the 1st method that will throw run-time exception)

It looks like you want to copy keys and values from a dictionary into an array of strings. Your last code example creates a single string, but a small modification will fix it:

int i=0;
var attributes = new object[dAttributes.Count];
string attribueKeyAndValues = "";
foreach (KeyValuePair<string,string> item in dAttributes)
{
    result[i] = item.Key + "=" + item.Value;
    i++;
}

As an aside, you might be better off using a string array instead of an object array:

int i=0;
var attributes = new string[dAttributes.Count];
string attribueKeyAndValues = "";
foreach (KeyValuePair<string,string> item in dAttributes)
{
    result[i] = item.Key + "=" + item.Value;
    i++;
}

Finally, you can do this using LINQ:

var attributes = dAttributes.Select(item => item.Key + "=" + item.Value).ToArray();

Or, if you really need it to be an object array instead of a string array, you can do this:

var attributes = dAttributes.Select(item => item.Key + "=" + item.Value).ToArray<object>();

You might want to have a look at dynamic objects, where you can add whatever you want however you want (well, with the usual caveats).

You can find more about them here

You can then do things like:

dynamic sampleObject = new ExpandoObject();
sampleObject.number = 10;
sampleObject.Increment = (Action)(() => { sampleObject.number++; });

Ok, with the help of ASH's answer I worked out it successfully with one more friend of mine,

public static class AttributeExtensions
    {
        public static object ToAttributeArray(this DAttributes dealAttr)
        {
            var objectsColl = dealAttr.dAttributes.Select(x => x.Key + "=" + x.Value);

            var objArray = objectsColl.Cast<object>();
            return  objArray.ToArray<object>();

        }
    }

Now its working properly, thanks you guys :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM