I have my foreach loop:
var i = 0;
foreach (DataRow data in result.Tables[0].Rows)
{
var periodStartDate = Convert.ToDateTime(data.Table.Rows[i]["Date"].ToString().Remove(10));
var periodEndDate = Convert.ToDateTime(data.Table.Rows[i]["Date"].ToString().Remove(0, 12));
calc.PeriodStartDate = periodStartDate;
calc.PeriodEndDate = periodEndDate;
calc.InvoiceAmount = Convert.ToDecimal(data.Table.Rows[i]["Invoice amount"].ToString());
calc.InterestRate = Convert.ToDecimal(data.Table.Rows[i]["Interest rate"].ToString());
calc.InterestAmount = Convert.ToDecimal(data.Table.Rows[i]["Interest amount"].ToString());
calc.Amortization = Convert.ToDecimal(data.Table.Rows[i]["Amortization"].ToString());
calc.PresentValue = Convert.ToDecimal(data.Table.Rows[i]["Capital balance"].ToString());
calc.StartValue = Convert.ToDecimal(data.Table.Rows[0]["Capital balance"].ToString());
cList.Add(calc);
i++;
}
I wanna do the same but in a for loop instead. Tried this (don't work because it can't find data (obviously):
for (int i = 0; i < result.Tables[0].Rows.Count; i++)
{
var periodStartDate = Convert.ToDateTime(data.Table.Rows[i]["Date"].ToString().Remove(10));
var periodEndDate = Convert.ToDateTime(data.Table.Rows[i]["Date"].ToString().Remove(0, 12));
calc.PeriodStartDate = periodStartDate;
calc.PeriodEndDate = periodEndDate;
calc.InvoiceAmount = Convert.ToDecimal(data.Table.Rows[i]["Invoice amount"].ToString());
calc.InterestRate = Convert.ToDecimal(data.Table.Rows[i]["Interest rate"].ToString());
calc.InterestAmount = Convert.ToDecimal(data.Table.Rows[i]["Interest amount"].ToString());
calc.Amortization = Convert.ToDecimal(data.Table.Rows[i]["Amortization"].ToString());
calc.PresentValue = Convert.ToDecimal(data.Table.Rows[i]["Capital balance"].ToString());
calc.StartValue = Convert.ToDecimal(data.Table.Rows[0]["Capital balance"].ToString());
cList.Add(calc);
}
How can I re-write my for loop so it matches my foreach loop?
foreachover theRowsso that you could take the table and then iterate over its rows using an indexer? Why aren't you simply doingdata["Date"]etc. in yourforeachcode?calcin each iteration of the loop (unless it's astruct), otherwise you'll have a nice list of completely identical values incList. And of course, there's no reason to convert the value to string and then to a given data type - you can cast it right away, eg.(decimal)row["Capital balance"].(DateTime)data["Date"]. Assuming you do actually have a structure in the data table. If it's all made of strings, you're going to have to do the parsing (but you still should do a cast, rather thanToString).