代码之家  ›  专栏  ›  技术社区  ›  Mike

来自多个数组的foreach循环c#

  •  2
  • Mike  · 技术社区  · 16 年前

    请批评我的代码。

            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);                
            }
    
    7 回复  |  直到 16 年前
        1
  •  12
  •   SLaks    16 年前

    您可以使用LINQ:

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

    我是这么想的 conflicts 是一个 List<TextBox> ,具有 AddRange Add 在(单个)循环中。
    如果你在创造 ,(或者如果它开始为空),您可以调用 .ToList() 相反。

        2
  •  3
  •   ljs TheVillageIdiot    16 年前

    另一个.net 3.5approach:-

    conflicts.AddRange(from textBox in vert.Concat(hort).Concat(cube)
                       where textBox.Text == box.Text
                       select textBox);
    
        3
  •  1
  •   Randolpho    16 年前

    如果出于任何原因不能使用LINQ(我强烈建议您这样做),您可以将数组搜索设置为一个方法。例如:

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

    FindConflicts(vert, conflicts, box.Text);
    FindConflicts(hort, conflicts, box.Text);
    FindConflicts(cube, conflicts, box.Text);
    
        4
  •  1
  •   JeppeSN    16 年前

      foreach (var direction in new[] { vert, hort, cube })
        foreach (TextBox tb in direction)
          if (tb.Text == box.Text)
            conflicts.Add(tb);
    
        5
  •  0
  •   Justin Niessner    16 年前
    var unionResult = vert.Concat(hort).Concat(cube)
    
    foreach(TextBox tb in unionResult)
        if(tb.Text == box.Text)
            conflicts.Add(tb);
    
        6
  •  0
  •   48klocs    16 年前

    use Enumerable.Concat to glue them together 如果您使用的是.Net 3.5或更高版本。

    foreach (TextBox tb in vert.Concat(hort).Concat(cube))
    
        7
  •  -1
  •   Daniel Bern    16 年前

    这将帮助您在文本框中使用foreach来选择更有效的应用程序模型w/o。使用延迟计算解决了对象缩减的问题,但不能改善逻辑人。