列表没有在C#中添加所有值
我尝试下面的代码创建json代码,代码工作正常。
我是从db加载值,但最后一个值只有我得到一个输出。未添加的值。
DataTable dt = new DataTable(); var objectToSerialize = new RootObject(); SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString()); SqlCommand command = new SqlCommand("select * from IFlicksMenu", connection); SqlDataAdapter da = new SqlDataAdapter(command); da.Fill(dt); foreach (DataRow dr in dt.Rows) { foreach (DataColumn col in dt.Columns) { objectToSerialize.contacts = new List { new Cont { sno = dr["Cinema"].ToString(), name = dr["Gallery"].ToString(), address = dr["star"].ToString(), gender = dr["video"].ToString(), em = dr["em"].ToString(), phone=new Phone { mobile=dr["phonone"].ToString() } }, }; } JavaScriptSerializer serializer = new JavaScriptSerializer(); Response.Write(serializer.Serialize(new { item = objectToSerialize.contacts })); }
输出是
{ "item":[ { "phone":{ "mobile":"99528748474" }, "sno":"ACTRESS", "name":"ACTRESS", "em":"scd", "address":"ACTRESS", "gender":"TRAILER" } ] }
当您想要在循环开头创建并继续添加到列表时,可以为每个项重新创建contacts
:
var items = new List(); foreach (DataRow dr in dt.Rows) { items.Add(new Cont{ sno = dr["Cinema"].ToString(), name = dr["Gallery"].ToString(), address = dr["star"].ToString(), gender = dr["video"].ToString(), em = dr["em"].ToString(), phone = new Phone{ mobile=dr["phonone"].ToString() } }); } objectToSerialize.contacts = items;
你还需要删除内部循环
foreach (DataColumn col in dt.Columns)
因为它会有效地将行数乘以列数
您在每次迭代中实例化foreach
列表,因此它需要最后的迭代。您可以在foreach
之外定义List对象,在foreach
定义值
List ContCollection = new List (); foreach (DataRow dr in dt.Rows) { foreach (DataColumn col in dt.Columns) { ContCollection.Add(new Cont(){ sno = dr["Cinema"].ToString(), name = dr["Gallery"].ToString(), address = dr["star"].ToString(), gender = dr["video"].ToString(), em = dr["em"].ToString(), phone=new Phone { mobile=dr["phonone"].ToString() } }); } objectToSerialize.contacts = ContCollection; JavaScriptSerializer serializer = new JavaScriptSerializer(); Response.Write(serializer.Serialize(new { item = objectToSerialize.contacts })); }
尝试使用
objectToSerialize.contacts.Add( new List { new Cont{ sno = dr["Cinema"].ToString(), name = dr["Gallery"].ToString(), address = dr["star"].ToString(), gender = dr["video"].ToString(), em = dr["em"].ToString(),phone=new Phone{mobile=dr["phonone"].ToString()} }, });
代替
上述就是C#学习教程:列表没有在C#中添加所有值分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
objectToSerialize.contacts = new List { new Cont{ sno = dr["Cinema"].ToString(), name = dr["Gallery"].ToString(), address = dr["star"].ToString(), gender = dr["video"].ToString(), em = dr["em"].ToString(),phone=new Phone{mobile=dr["phonone"].ToString()} }, };
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/987951.html