简体   繁体   中英

Can i able to store each item in a json array inside a foreach loop in c# web api?

I want to store each item to a json array which is placed inside a foreach loop.

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,
                            }
                          },
                        }
                      } 

Here.i have a foreach loop for getting details about a theatre,i want to store these datas to a json array,based on the condition.Right now i can only managed to store 1 data,ie the last one.

The issue is that this code creates a new array with every iteration of the loop. Try something like:

    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*/ });
    }

If the datagrid row object is of strongly typed then you can covert the rows collection to enumerable strongly typed. Over the collection you can use Linq query to filter those records which matches the desired condition and in Select clause you can serialize the object using JsonCovert.SerializeObject method (from Newton.Json assembly).

For ex :
List theatres = alltheatre.Rows as List;
var serializedTheatres = theares.Where(t => t.MouvieId > 100).Select(t => JsonCovert.SerializeObject(t)).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM