Unnikrishnan.S
Unnikrishnan.S

Reputation: 185

how can i store each items in a json array using c#

I want to store each item to a json array which is placed inside a foreach loop.How can i possible?

Presently my code is

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();

                 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 tried to store each data to a json array,but i can only managed to store 1 data,ie the last one.How to resolve this issue.

Upvotes: 0

Views: 162

Answers (2)

Matias Cicero
Matias Cicero

Reputation: 26281

I would use LINQ's Select to map each row:

IEnumerable<object> mapped = alltheatre.Rows.Select(row => new 
{
     Name = row["TheatreName"].ToString(),
     Theatrdetailsid = row["TheatreDetailsId"].ToString()
     // ...
});

If you need it to be in a raw array, you can call ToArray():

object[] mappedArray = mapped.ToArray();

Upvotes: 1

krillgar
krillgar

Reputation: 12805

You need to declare your new collection outside of the foreach loop. You only have one, because creates a new array every time.

Instead of an array, you should use a List<T>. This will be much easier, unless you want to use LINQ or create an array the size of the Rows collection.

var array = new List<object>();

foreach (var row in alltheatre.Rows)
{
    // Get your properties

    array.Add(new 
    {
        // Set your properties
    });
}

Upvotes: 1

Related Questions