C# 我是否能够在c web api中的foreach循环内将每个项存储在json数组中?
我想将每个项存储到一个json数组中,该数组位于foreach循环中C# 我是否能够在c web api中的foreach循环内将每个项存储在json数组中?,c#,C#,我想将每个项存储到一个json数组中,该数组位于foreach循环中 object array=""; foreach (DataRow drow1 in alltheatre.Rows) { string theatname = drow1["TheatreName"].ToString(); string latitude = drow1["Latitude"].ToString(); string lo
object array="";
foreach (DataRow drow1 in alltheatre.Rows)
{
string theatname = drow1["TheatreName"].ToString();
string latitude = drow1["Latitude"].ToString();
string longitude = drow1["Longitude"].ToString();
string theatname = drow1["TheatreName"].ToString();
string theatid = drow1["TheatreDetailsId"].ToString();
string theataddre = drow1["TheatreAddress"].ToString();
string cntctnu = drow1["ContactNum"].ToString();
string theatimg = drow1["TheatreImage"].ToString();
string descr = drow1["TheatreDesc"].ToString();
string mouvieid = drow1["MovieMasterId"].ToString();
if (mouvieid <100)
{
array = new[]
{
new
{
Name = theatname,
Theatrdetailsid=theatid,
image=theatimg,
lat=latitude,
longi=longitude,
adress=theataddre,
contactnum=cntctnu,
desc=descr,
}
},
}
}
这里。我有一个foreach循环用于获取剧院的详细信息,我想根据条件将这些数据存储到json数组中。现在我只能存储1个数据,即最后一个数据 问题是这段代码在循环的每次迭代中都会创建一个新数组。 尝试以下方法:
using Newtonsoft.Json;
string[] array = new string[]{};
//data access and loop code
int id = int.Parse(mouvieId);
if (id < 100)
{
array[id] = JsonConvert.SerializeObject(new { Name = theatname /*rest of properties*/ });
}
如果datagrid行对象是强类型的,则可以将行集合转换为可枚举的强类型。在集合上,您可以使用Linq query来过滤那些与所需条件匹配的记录,并且在Select子句中,您可以使用Newton.Json汇编中的jsonconvert.SerializeObject方法序列化对象 例如: 列出剧院=所有剧院。行作为列表; var serializedTheatres=theares.Wheret=>t.mouveid>100.Selectt=>jsoncort.SerializeObjectt.ToList