0

I have a string "hello", and a integer 1.

I want to convert them into

new { hello= 1 } 

dynamically, and without using any condition like

switch(p1){
case "hello":
return new {hello=p2};
}

as there is many different string and I need to put many items into a super object set like

var emotion = {smile=1,angry=2,worry=3}

the problem is smile, angry and worry was string. but after added to emotion, they are not string, but just an index (like dictionary, however dictionary's index also has dataType, which is not my expected result)

Is it possible?

--- Updated --- i have added a function to specify the expected output.

private void Question_1()
{
    //i have
    string a = "hello";
    int b = 1;
    // i want to convert a and b to new {a = b} programmatically, for example i can convert a and b to a Tuple like
    Tuple<string, int> x = new Tuple<string, int>(a,b);
    //but i dont know how to to convert it to new {a = b}, as i need to put the string "hello" as key to new {a=b}
    var result = new { hello = b }; //you can see i can put b after =, but i can never put the string hello at the left
}
private void Question_2()
{
    //and the final should be like this
    List<Tuple<string, int>> list = new List<Tuple<string, int>>() {
        new Tuple<string,int>("smile",1),
        new Tuple<string,int>("cry",2),
        new Tuple<string,int>("worry",3)
    };
    foreach (Tuple<string, int> item in list)
    {
        //adding item's string and int into result and finally the result is
    }
    //the final result
    var finalResult = new { smile = 1, cry = 2, worry = 3 };
}
8
  • 1
    you can use enum Commented Jan 10, 2017 at 3:30
  • 1
    If the text and values are dynamic, you could try a dictionary. Commented Jan 10, 2017 at 3:34
  • 1
    the input string is random, thus it will be a very large enum, i dont think it work... Commented Jan 10, 2017 at 3:37
  • the main point is that i dont want to hardcode anything(for example a enum ) in order to convert the object. Thanks Commented Jan 10, 2017 at 3:39
  • 1
    Sounds much like this question: stackoverflow.com/questions/4938397/… Commented Jan 10, 2017 at 3:42

4 Answers 4

1

Use .NET naming conventions for enums: They should be Pascal Notation.

enum Emotion
{
    Smile = 1, Angry = 2, Worry = 3
}

var l = new List<Emotion> { Emotion.Angry, Emotion.Smile, Emotion.Worry };

You can also use a friendly name for your enum with the DesriptionAttribute like this:

enum Emotion
{
    [Description("Smiling")]
    Smile = 1,
    [Description("Angry Type")]
    Angry = 2,
    [Description("Worry Type")]
    Worry = 3
}
Sign up to request clarification or add additional context in comments.

Comments

1

Any reason you can't just use a dictionary?

var hi = new Dictionary<string,int>();
hi[p1] = p2;
return hi; // Would serialize the same way as your anonymous object

If not, then you could use the expando object to dynamically set properties at runtime.

var hi = new ExpandoObject() as IDictionary<string, object>;
hi.Add(p1, p2);
var p2Value = (int)((dynamic)hi).hello;

4 Comments

hi dictionary doesn't work actually, as it is <string,int>, what i wanted is new{ hello=1}, note that hello actully isn't a string in the output. the objective is to convert one string and one int (in fact it is not just int, as it can be other types too) into > new {stringValue: intValue}, just to emphasize that stringValue is actully not string, it is something like index of that thing (i really don't know if i should call it array )
Dictionary is a generic object...you can define it as anything you like <string,object>, <object,object>, anything that fits your requirements. If you're returning this as part of Web API or MVC actions, then the serialization to JSON should be very similar if not the same.
yes, but i dont know what is the datatype of hello in this object ==> new {hello=1} , how to implement a dictionary which the input is a string and a integer, and the output is : var output = new {stringVal=intValue} .
Guess i'm missing something. Seems that "hello" is either a string or must be converted to a string to be the key value of your anonymous object. In either case, I don't see why neither of these techniques can't work (since either can be converted to have the "p2" value be int, string, object, or any data type you want.
0

You can use ExpandoObject.

class Program
    {
        static dynamic obj = new ExpandoObject();
        static void Main(string[] args)
        {
            AddProperty("City", "Sydney");
            AddProperty("Country", "Australia");
            AddProperty("hello", 1);

            Console.WriteLine(obj.City);
            Console.WriteLine(obj.Country);
            Console.WriteLine(obj.hello);

            //We can even use dynamic property names ( e.g. cityProp in below example ) 
            IDictionary<string, object> dic = obj as IDictionary<string, object>;
            Console.WriteLine("City is : " + dic[cityProp]);
        }

        public static void AddProperty(string propertyName, object value)
        {
            IDictionary<string, object> a = obj as IDictionary<string, object>;
            a[propertyName] = value;
        }
    }

1 Comment

it is not worked, i need it able to be accepted by Url.Action("action","controller", x), where x is thing that i'm trying to create dynamically . i don't know if dynamic too complex or what. but Url.Action dont know how to read it
0
dynamic emotion = new { smile = 1, angry = 2, worry = 3 };
Console.WriteLine(emotion.smile);

Like this?

Edit: Based on your comment on another answer:

it is not worked, i need it able to be accepted by Url.Action("action","controller", x), where x is thing that i'm trying to create dynamically . i don't know if dynamic too complex or what. but Url.Action dont know how to read it

There's obviously more to the question than just C#, clearly this an MVC question. You should really add as much information as you can about what you need.

Your answer is probably here:

https://stackoverflow.com/a/15112223/1685167

The @Url.Action() method is proccess on the server side, so you cannot pass a client side value to this function as a parameter.

4 Comments

not really, assuming i have "smile", "angry", "worry, and 1, 2 ,3. i need to implement a program to convert them emotion dynamically
i am not sure why you think i am passing client side value to Url.Action. new { para=1,para2=2,para3=3} is a regular server side object. I can implement it manually and put it into Url.Action without any issue. my question is to create the new { para=1,para2=2,para3=3} for Url.Action. And I think creating new { para=1,para2=2,para3=3} is C# (converting a group of string and int to that object)
@SKLTFZ well first of all, since you need it able to be accepted by Url.Action("action","controller", x) you should add appropriate tags and more information accordingly. Second, "new { para=1,para2=2,para3=3}" is not "converting a group of string and int to that object". They are simply variable names and values in an object. This is what makes what you are saying incredibly confusing. And since you are refusing every other answer to your question it is probably because of a lack of information on your part.
objective is about accepting by the url.action. but normally you can still check the output during debug. the answer that provided above isnt able to be the same as new{p1=1,p2=2,p3=3}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.