如何在此foreach循环中添加计数器?

时间:2017-05-03 10:18:20

标签: c# loops foreach counter

如何在此代码中添加计数器?

foreach(DataSet1.Save_PropertyRow r in DT)
{
    var testProperty = CreateTestAOProperty(r.ADDRESS, r.Adjustments...);
    var savePropertyResult = _Client.SaveProperty(credentials, testProperty);
Console.WriteLine("Save Property result: \"{0}\" with message \"{1}\"", savePropertyResult.Status, savePropertyResult.Message);

LogMessageToFile(CaseID, "Property Results Saved to log");

Console.ReadLine();

1 个答案:

答案 0 :(得分:1)

在循环外定义一个整数,并在循环内增加它。

int count = 0;
foreach(value in array)
{
    Console.WriteLine("Current count: {0}", count);
    //Do your thing.
    count++;
}

使用for循环而不是foreach,它有你的计数:

for(int i = 0; i < array.length; i++)
{
    var item = array[i];
    Console.WriteLine("Current count: {0}", i + 1);
    //Do your thing.
}