2012-03-21 77 views
0

我有一個List<T>,它具有辦公室位置的屬性,我想在運行時爲每個列表項添加一個新屬性。使用4.0在運行時將屬性添加到列表<T>

目前我有:

//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對象。或者也許有更好的方法來一起做這件事。

+2

不知道你使用的是什麼版本的.NET的,但你有沒有考慮動態對象? – CodingGorilla 2012-03-21 18:23:32

+0

我想過,但會佔用更多的內存比'List >' – bflemi3 2012-03-21 18:24:40

+1

我在想ExpandoObject,它既是字典也是動態的 – 2012-03-21 18:28:09

回答

4

匿名類型應該在你的情況下正常工作:

var locations = mlaLocations.ToList().Select(x => new { 
     where = x.Address.Street1 + ", " + x.Address.City, 
     email =x.Email } 
); 
+1

-1:這甚至不像編譯器碼。 – 2012-03-21 18:31:59

+0

謝謝。固定代碼。 – 2012-03-21 18:35:36

+0

謝謝阿列克謝,我喜歡這個代碼比我的更好,更乾淨:) – bflemi3 2012-03-21 18:44:58

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; 
相關問題