简体   繁体   中英

C# Array Don't Work at for loop

My Code:

DataTable dt = fs.DataTable;
int columnsNumber = dt.Columns.Count;
string[] array = new string[columnsNumber];

for (int k=0; k==columnsNumber; k++)
{ 
    array[k] = dt.Columns[k].ColumnName;
}


foreach (var item in array)
{
    MessageBox.Show(item);
}

MessageBox has displaying the blank message.

If I have run this code, no problem;

array[1] = dt.Columns[1].ColumnName; 
array[2] = dt.Columns[2].ColumnName; 
array[3] = dt.Columns[3].ColumnName;

This work. What is the problem ?

Your cicle just checking k==kolonSayisi :

for (int k=0; k==kolonSayisi; k++)
{ 
    array[k] = dt.Columns[k].ColumnName;
}

I think you should write it like this:

for (int k=0; k < columnsNumber; k++)
{ 
    array[k] = dt.Columns[k].ColumnName;
}

You have included a == operator in for loop where you should be using <

Change

for (int k=0; k==kolonSayisi; k++)

to

for (int k=0; k<kolonSayisi; k++)

You can also use this way

var listToArray = new listToArray<string>();
foreach (DataColumn dataCol in dt.Columns)
    listToArray.Add(dataCol.ColumnName);
listToArray.ToArray();

Hope it helps.

You can use like this:

       DataTable table = new DataTable();

        table.Columns.Add("col1");
        table.Columns.Add("col2");
        table.Columns.Add("col3");

        var array = table.Columns
            .Cast<DataColumn>()
            .Select(c => c.ColumnName)
            .ToArray();

        foreach(var item in array)
        {
            MessageBox.Show(item);
        }

A for loop works the following way:

In the parentheses the first part defines a counting or increment variable and sets the starting value. The second part is the cancel condition. You can read it like: if condition is false then stop the loop. The third part defines the step size, how you want to increment your variable.

Now if you look at your condition k==columnsNumber you are trying to check if k equals the number. In the first iteration where k is 0 it will return false if columnsNumber is not 0. So your loop will stop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM