0

I have a list of arrays, of which i want to take one value from each array and build up a JSON structure. Currently for every managedstrategy the currency is always the last value in the loop. How can i take the 1st, then 2nd value etc while looping the names?

List<managedstrategy> Records = new List<managedstrategy>();
        int idcnt = 0;
        foreach (var name in results[0])
        {
            managedstrategy ms = new managedstrategy();
            ms.Id = idcnt++;
            ms.Name = name.ToString();

            foreach (var currency in results[1]) {
               ms.Currency = currency.ToString();
            }

            Records.Add(ms);
        }

        var Items = new
        {
            total = results.Count(),
            Records
        };

        return Json(Items, JsonRequestBehavior.AllowGet);

JSON structure is {Records:[{name: blah, currency: gbp}]}

Marc Howard
  • 395
  • 2
  • 6
  • 25

2 Answers2

0

Assuming that I understand the problem correctly, you may want to look into the Zip method provided by Linq. It's used to "zip" together two different lists, similar to how a zipper works.

A related question can be found here.

Community
  • 1
  • 1
BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56
0

Currently, you are nesting the second loop in the first, resulting in it always returning the last currency, you have to put it all in one big for-loop for it to do what you want:

for (int i = 0; i < someNumber; i++)
{
    // some code
    ms.Name = results[0][i].ToString();
    ms.Currency = results[1][i].ToString();
}
ThreeFx
  • 7,250
  • 1
  • 27
  • 51