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.

Share Improve this question edited Feb 4 at 3:57 Ivan Petrov 5,0702 gold badges11 silver badges23 bronze badges asked Feb 4 at 3:18 devChingdevChing 52 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 0

You 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