【发布时间】:2017-05-24 11:03:40
【问题描述】:
我有一个字符串“hello”和一个整数 1。
我想把它们转换成
new { hello= 1 }
动态地,并且不使用像
这样的任何条件switch(p1){
case "hello":
return new {hello=p2};
}
因为有许多不同的字符串,我需要将许多项目放入一个超级对象集中,例如
var emotion = {smile=1,angry=2,worry=3}
问题是微笑,生气和担心是字符串。但是加上情感之后,它们不是字符串,而只是一个索引(就像字典一样,但是字典的索引也有dataType,这不是我的预期结果)
有可能吗?
--- 更新 --- 我添加了一个函数来指定预期的输出。
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 };
}
【问题讨论】:
-
你可以使用
enum -
如果文本和值是动态的,你可以试试字典。
-
输入字符串是随机的,因此它会是一个非常大的枚举,我认为它不起作用...
-
重点是我不想硬编码任何东西(例如枚举)来转换对象。谢谢
-
听起来很像这个问题:stackoverflow.com/questions/4938397/…
标签: c# asp.net-mvc