我有一个List<T>
具有办公地点的属性,我想在运行时为每个列表项添加一个新属性。使用4.0
目前我所拥有的:
//create json object for bing maps consumption
List<Dictionary<string, string>> locations = new List<Dictionary<string, string>>();
mlaLocations.ToList().ForEach(x => {
locations.Add(new Dictionary<string, string>() {
{"where", x.Address.Street1 + ", " + x.Address.City + ", " + x.Address.State + " " + x.Address.PostalCode},
{"email", x.Email},
{"fax", x.Fax},
{"href", "http://www.mlaglobal.com/locations/" + Utils.CleanString(x.Name) + "/" + x.Id},
{"name", x.Name},
{"streetAddress", x.Address.Street1},
{"city", x.Address.City},
{"state", x.Address.State},
{"zip", x.Address.PostalCode}
});
});
JavaScriptSerializer jss = new JavaScriptSerializer();
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"","var locations = " + jss.Serialize(locations.ToList()),true);
我想要做的是elimate List<Dictionary<string, string>> locations
,只需将href属性添加到mlaLocations对象即可。或者也许有更好的方法可以一起完成这一切。
答案 0 :(得分:4)
匿名类型应该可以正常使用:
var locations = mlaLocations.ToList().Select(x => new {
where = x.Address.Street1 + ", " + x.Address.City,
email =x.Email }
);
答案 1 :(得分:2)
使用ExpandoObject和dynamic
:
List<dynamic> locations = //whatever
foreach (dynamic location in locations)
location.href = "http://www.mlaglobal.com/locations/"
+ Utils.CleanString(location.Name) + "/" + location.Id;