Reputation: 24478
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;
Upvotes: 15
Views: 6576
Reputation: 68737
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()));
Upvotes: 29
Reputation: 390
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()));
Upvotes: 1
Reputation: 269578
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()));
Upvotes: 5
Reputation: 19117
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());
}
Upvotes: 3