how to convert an instance of an anonymous type to a NameValueCollection

≯℡__Kan透↙ 提交于 2020-01-23 04:48:08

问题


Suppose I have an anonymous class instance

var foo = new { A = 1, B = 2};

Is there a quick way to generate a NameValueCollection? I would like to achieve the same result as the code below, without knowing the anonymous type's properties in advance.

NameValueCollection formFields = new NameValueCollection();
formFields["A"] = 1;
formFields["B"] = 2;

回答1:


var foo = new { A = 1, B = 2 };

NameValueCollection formFields = new NameValueCollection();

foo.GetType().GetProperties()
    .ToList()
    .ForEach(pi => formFields.Add(pi.Name, pi.GetValue(foo, null).ToString()));



回答2:


Another (minor) variation, using the static Array.ForEach method to loop through the properties...

var foo = new { A = 1, B = 2 };

var formFields = new NameValueCollection();
Array.ForEach(foo.GetType().GetProperties(),
    pi => formFields.Add(pi.Name, pi.GetValue(foo, null).ToString()));



回答3:


Just about what you want:

Dictionary<string, object> dict = 
       foo.GetType()
          .GetProperties()
          .ToDictionary(pi => pi.Name, pi => pi.GetValue(foo, null));

NameValueCollection nvc = new NameValueCollection();
foreach (KeyValuePair<string, object> item in dict)
{
   nvc.Add(item.Key, item.Value.ToString());
}



回答4:


I like the answer Yurity gave with one minor tweak to check for nulls.

var foo = new { A = 1, B = 2 };

NameValueCollection formFields = new NameValueCollection();

foo.GetType().GetProperties()
 .ToList()
 .ForEach(pi => formFields.Add(pi.Name, (pi.GetValue(foo, null) ?? "").ToString()));


来源:https://stackoverflow.com/questions/2838398/how-to-convert-an-instance-of-an-anonymous-type-to-a-namevaluecollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!