Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop from multiple arrays c#

Tags:

arrays

c#

foreach

This should be a simple question. All I want to know is if there is a better way of coding this. I want to do a foreach loop for every array, without having to redeclare the foreach loop. Is there a way c# projects this? I was thinking of putting this in a Collection...?

Please, critique my code.

        foreach (TextBox tb in vert)
        {
            if (tb.Text == box.Text)                
                conflicts.Add(tb);                
        }
        foreach (TextBox tb in hort)
        {
            if (tb.Text == box.Text)                
                conflicts.Add(tb);                
        }
        foreach (TextBox tb in cube)
        {
            if (tb.Text == box.Text)
                conflicts.Add(tb);                
        }
like image 346
Mike Avatar asked Oct 17 '25 14:10

Mike


1 Answers

You can use LINQ:

conflicts.AddRange(
    vert.Concat(hort).Concat(cube)
        .Where(tb => tb.Text == box.Text)
); 

I'm assuming that conflicts is a List<TextBox>, which has an AddRange method. If it isn't, you'll need to call Add in a (single) loop.
If you're creating conflicts, (or if it starts empty), you can call .ToList() instead.

like image 180
SLaks Avatar answered Oct 20 '25 02:10

SLaks