简体   繁体   中英

foreach loop from multiple arrays c#

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);                
        }

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.

Another .net 3.5 approach:-

conflicts.AddRange(from textBox in vert.Concat(hort).Concat(cube)
                   where textBox.Text == box.Text
                   select textBox);

If you can't use LINQ for whatever reason (and I highly suggest you do) you could make your array searching a single method. For example:

public void FindConflicts(IEnumerable<TextBox> tbList, IList<TextBox> conflicts, string test)
{
   foreach(TextBox tb in tbList)
   {
      if(tb.Text == test)
      {
          conflicts.Add(tb);
      }
   }
}

And then call it like so:

FindConflicts(vert, conflicts, box.Text);
FindConflicts(hort, conflicts, box.Text);
FindConflicts(cube, conflicts, box.Text);
var unionResult = vert.Concat(hort).Concat(cube)

foreach(TextBox tb in unionResult)
    if(tb.Text == box.Text)
        conflicts.Add(tb);

如果您使用.Net 3.5或更高版本,您应该能够使用Enumerable.Concat将它们粘合在一起

foreach (TextBox tb in vert.Concat(hort).Concat(cube))

There are of course many ways to write this, but you could also do

  foreach (var direction in new[] { vert, hort, cube })
    foreach (TextBox tb in direction)
      if (tb.Text == box.Text)
        conflicts.Add(tb);

If you try to create Sudoku game(mentioned in comments) first read about Permutation group and Combinatorics. This will help you to choose more efficient Application Model w/o using foreach on text boxes. Using lazy computation resolve the problem with object reduction but not improve your logics man.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM