简体   繁体   English

C#数组在for循环中不起作用

[英]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. MessageBox已显示空白消息。

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 : 您的cicle仅检查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 < 您在for loop中包含了==运算符,应在其中使用<

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: for循环的工作方式如下:

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. 您可以这样阅读:如果condition为false,则停止循环。 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. 现在,如果您查看条件k==columnsNumber ,则尝试检查k是否等于数字。 In the first iteration where k is 0 it will return false if columnsNumber is not 0. So your loop will stop. 在k为0的第一次迭代中,如果columnsNumber不为0,它将返回false。因此,循环将停止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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