Craig Craig - 1 month ago 8
C# Question

Iterate through list, adding to array

I have a

List<PaymentObject>


A Payment Object consists of:


DateTime PaymentDate; Decimal Amount;


What I need to do is create an array that ends up like this:

s.Data = new Data(new object[,]
{
{ new DateTime(1970, 9, 27), 0 },
{ new DateTime(1970, 10, 10), 0.6 },
{ new DateTime(1970, 10, 18), 0.7 },
{ new DateTime(1970, 11, 2), 0.8 },
{ new DateTime(1970, 11, 9), 0.6 },
{ new DateTime(1970, 11, 16), 0.6 },
{ new DateTime(1970, 11, 28), 0.67 },
{ new DateTime(1971, 1, 1), 0.81 },
{ new DateTime(1971, 1, 8), 0.78 },
{ new DateTime(1971, 1, 12), 0.98 },
{ new DateTime(1971, 1, 27), 1.84 },
{ new DateTime(1971, 2, 10), 1.80 },
{ new DateTime(1971, 2, 18), 1.80 },
{ new DateTime(1971, 2, 24), 1.92 },
{ new DateTime(1971, 3, 4), 2.49 },
{ new DateTime(1971, 3, 11), 2.79 },
{ new DateTime(1971, 3, 15), 2.73 },
{ new DateTime(1971, 3, 25), 2.61 },
{ new DateTime(1971, 4, 2), 2.76 },
{ new DateTime(1971, 4, 6), 2.82 },
{ new DateTime(1971, 4, 13), 2.8 },
{ new DateTime(1971, 5, 3), 2.1 },
{ new DateTime(1971, 5, 26), 1.1 },
{ new DateTime(1971, 6, 9), 0.25 },
{ new DateTime(1971, 6, 12), 0 }
});


How can I foreach through my list, and add each item to the Array?

Answer

One way might look like:

var paymentObjectList = new List<PaymentObject>();
// assuming the above gets populated at some point 

object[,] dataArray = new object[paymentObjectList.Count, 2];
int listIndex = 0;
foreach (var paymentObject in paymentObjectList)
{
    dataArray[listIndex, 0] = paymentObject.PaymentDate;
    dataArray[listIndex, 1] = paymentObject.Amount;
    listIndex++;
}

// resuming your original code
s.Data = new Data(dataArray);