Foreach, optional conditional expression

Sorry, I hope that no one will notice me about the question about noob, I do not yet have a C # ref> <

Is there a way to put an additional conditional statement inside the foreach loop, for example:

string[] giggles = new string[6] { "one", "two", "three", "four", "five", "Six" };
    int i = 0;

    foreach (string gig in giggles && i < 4)
    {
        lblDo.Text = gig;
        i++;
    }

This obviously doesn't work, but is there something similar I can use, or am I sticking to using the if / break statement in a loop? Thank!

+3
source share
7 answers

You will need to use if / break or the for loop. The foreach loop is almost intentionally limited because the dot simply iterates over the enumerated collection *. If you need more concise contour control, you should use for loops, while loops or do-while loops.

* in fact, all that the GetEnumerator () method has.

+4

:

foreach (string gig in giggles.Take(4))
{
    //..
}

, giggles. Take() LINQ, , .

, . , :

int i = 0;
foreach (string gig in giggles.Where( x => i <= 4))
{
    lblDo.Text = gig;
    i++;
}
+17

for foreach.

foreach , IEnumerable. for, , .

:

string[] giggles = new string[6] { "one", "two", "three", "four", "five", "Six" };

for (int i = 0; i < 4; ++i)
{
    lblDo.Text = giggles[i];
}

"" - , 4 , :

for (int i = 0; i < giggles.Length && i < 4; ++i)
{
    lblDo.Text = giggles[i];
}
+1

for ?

for(int i = 0; i < 4 || i < giggles.Count; i++)
{
    giggles[i].doSomething();
}
+1

if . break , :

:

foreach (string gig in giggles)
{
    if(i >= 4)
    {
        break;
    }
    lblDo.Text = gig;
    i++;
}
+1

It really depends on what you are trying to do. You can use Take () in this example.

string[] giggles = new string[6] { "one", "two", "three", "four", "five", "Six" };


foreach (string gig in giggles.Take(4))
{
    lblDo.Text = gig;

}

But if you want, for example, lines starting with "f", you can use

    foreach (string gig in giggles.Where(s => s.StartsWith("f")  ))
        {
            Console.WriteLine(gig);

        }
+1
source

If true, the foreach loop may work with additional conventions. Where functions may contain conditions that do not affect the list itself:

For your need you can use something like this:

int i = 0;

foreach (var gig in giggles.Where( p => i < 4 ))
{
    ...
    i++;
}

Recently, I used it in such a way as to break the loop into external conditions:

bool saveOk = true;

foreach ( var item in myList.Where( p=> saveOk ))
{
    saveOk = saveTheItem(item);
}
+1
source

Source: https://habr.com/ru/post/1784786/


All Articles