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 };
}
SKLTFZ
  • 841
  • 2
  • 10
  • 30
  • 1
    you can use `enum` – Mohit S Jan 10 '17 at 03:30
  • 1
    If the text and values are dynamic, you could try a dictionary. –  Jan 10 '17 at 03:34
  • 1
    the input string is random, thus it will be a very large enum, i dont think it work... – SKLTFZ Jan 10 '17 at 03:37
  • the main point is that i dont want to hardcode anything(for example a enum ) in order to convert the object. Thanks – SKLTFZ Jan 10 '17 at 03:39
  • 1
    Sounds much like this question: http://stackoverflow.com/questions/4938397/dynamically-adding-properties-to-an-expandoobject – Bonelol Jan 10 '17 at 03:42
  • Possible duplicate of [Passing dynamic javascript values using Url.action()](http://stackoverflow.com/questions/15112055/passing-dynamic-javascript-values-using-url-action) – Tyress Jan 10 '17 at 08:02
  • What do you mean by `they are not string`? What do you want it to be exactly? How does the anonymous object should look like? If I understand correctly you "hello" string is kept in some variable and you want hello to become the property name and not the variable name itself. is it? – RBT Jan 10 '17 at 08:33
  • Do you want something like this - `var myVar = "smile"; var myVar2 = "angry"; var myVar3 = "worry"; var emotion = new { myVar = 1, myVar2 = 2, myVar3 = 3 };` and then emotion should actually become something like this? `//emotion = new { smile = 1, angry = 2, worry = 3 };` This way the actually properties you access later on in the code are `emotion.smile`, `emotion.angry`, `emotion.worry`? – RBT Jan 10 '17 at 08:54

4 Answers4

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
}
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
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;
Jason W
  • 13,026
  • 3
  • 31
  • 62
  • hi dictionary doesn't work actually, as it is , 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 ) – SKLTFZ Jan 10 '17 at 04:39
  • Dictionary is a generic object...you can define it as anything you like , , 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. – Jason W Jan 10 '17 at 19:22
  • 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} . – SKLTFZ Jan 11 '17 at 03:28
  • 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. – Jason W Jan 11 '17 at 19:58
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;
        }
    }
user2243747
  • 2,767
  • 6
  • 41
  • 61
  • 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 – SKLTFZ Jan 10 '17 at 07:22
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.

Community
  • 1
  • 1
Tyress
  • 3,573
  • 2
  • 22
  • 45
  • not really, assuming i have "smile", "angry", "worry, and 1, 2 ,3. i need to implement a program to convert them emotion dynamically – SKLTFZ Jan 10 '17 at 07:56
  • 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 Jan 10 '17 at 08:17
  • @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. – Tyress Jan 10 '17 at 08:27
  • 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}. – SKLTFZ Jan 10 '17 at 11:31