Search code examples
c#for-loop

How to set condition in for loop?


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.


Solution

  • 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