【问题标题】:C# - Lambda syntax for looping over DataGridView.RowsC# - 用于循环 DataGridView.Rows 的 Lambda 语法
【发布时间】:2009-01-16 19:46:23
【问题描述】:

在 C# 中循环遍历 DataGridView 的每个 DataGridViewRow 的正确 lambda 语法是什么?例如,该函数根据 Cells[0] 中的某个值使行 .Visible = false。

【问题讨论】:

    标签: c# .net datagridview lambda


    【解决方案1】:

    查看我对这个问题的回答:Update all objects in a collection using LINQ

    这对于内置的 LINQ 表达式是不可能的,但是很容易自己编写代码。为了不干扰 List.ForEach.

    ,我调用了 Iterate 方法

    例子:

    dataGrid.Rows.Iterate(r => {r.Visible = false; });
    

    迭代源代码:

      public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T> callback)
        {
            if (enumerable == null)
            {
                throw new ArgumentNullException("enumerable");
            }
    
            IterateHelper(enumerable, (x, i) => callback(x));
        }
    
        public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
        {
            if (enumerable == null)
            {
                throw new ArgumentNullException("enumerable");
            }
    
            IterateHelper(enumerable, callback);
        }
    
        private static void IterateHelper<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
        {
            int count = 0;
            foreach (var cur in enumerable)
            {
                callback(cur, count);
                count++;
            }
        }
    

    【讨论】:

      【解决方案2】:

      好吧,可枚举没有内置的ForEach 扩展方法。我想知道一个简单的foreach 循环是否更容易?不过写起来很简单……

      一推,也许你可以在这里有用地使用Where

              foreach (var row in dataGridView.Rows.Cast<DataGridViewRow>()
                  .Where(row => (string)row.Cells[0].Value == "abc"))
              {
                  row.Visible = false;
              }
      

      但就我个人而言,我只会使用一个简单的循环:

              foreach (DataGridViewRow row in dataGridView.Rows)
              {
                  if((string)row.Cells[0].Value == "abc")
                  {
                      row.Visible = false;
                  }
              }
      

      【讨论】:

      • 这就是我现在正在做的事情(foreach)。只是想伸展我的大脑。在我当前的一个项目中,我不断地在这个 DataGridView 上循环。它变老了。哈哈
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-18
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      相关资源
      最近更新 更多