admin管理员组文章数量:1304543
This is my code
private void AddToDataTable(int j, bool condition)
{
for (int i = j; condition; j++ )
{
//do something
}
}
How do I declare the condition so that I can pass it to the for loop condition or how do I do it? My idea is to pass or change the condition to dataGridView.Rows.Count > i
or i % 3 !=0
.
This is my code
private void AddToDataTable(int j, bool condition)
{
for (int i = j; condition; j++ )
{
//do something
}
}
How do I declare the condition so that I can pass it to the for loop condition or how do I do it? My idea is to pass or change the condition to dataGridView.Rows.Count > i
or i % 3 !=0
.
3 Answers
Reset to default 0You can declare the method to accept Func<int,bool> condition
, instead of bool condition
You can also consider defining a delegate for the counter behavior - whether it's i++
or i--
for example:
public delegate void Counter(ref int i);
so the method looks like this:
private void AddToDataTable(int j, Func<int, bool> condition, Counter counter) {
for (int i = j; condition(i); counter(ref i)) {
Console.WriteLine(i);
}
}
Use would be:
AddToDataTable(0, i => i <= 9, (ref int i) => i++);
Console.WriteLine("----");
AddToDataTable(9, i => i >= 0, (ref int i) => i--);
Output:
0
1
2
3
4
5
6
7
8
9
----
9
8
7
6
5
4
3
2
1
0
You can implement the condition like this using a if statement:
private void AddToDataTable(int j, bool condition)
{
for (int i = j; condition; j++ )
{
//do something
if (condition == true){
// do some code for true case
}
if (condition == false){
// execute some code for false case
}
}
}
The issue in your code is that condition is a bool, which is evaluated once and does not change dynamically in the for loop. Instead of passing a bool, you should pass a function (Func<int, bool>) that evaluates the condition dynamically for each iteration.
static void Main()
{
// Example without DataGridView, using a simple count
Console.WriteLine("Loop while i < 5:");
AddToDataTable(0, i => i < 5);
Console.WriteLine("\nLoop while i is not a multiple of 3:");
AddToDataTable(0, i => i % 3 != 0);
}
private static void AddToDataTable(int j, Func<int, bool> condition)
{
for (int i = j; condition(i); i++)
{
Console.WriteLine($"i = {i}");
}
}
The second loop stops immediately because 0 % 3 == 0, making condition(0) return false. If you start from 1, it will loop until it encounters a multiple of 3:
AddToDataTable(1, i => i % 3 != 0);
本文标签: cHow to set condition in for loopStack Overflow
版权声明:本文标题:c# - How to set condition in for loop? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741788272a2397514.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论