C# – 用于在DataGridView.Rows上循环的Lambda语法

C#中用于循环DataGridView的每个DataGridViewRow的正确lambda语法是什么? 作为一个例子,假设函数根据Cells [0]中的某个值使行.Visible = false。

请参阅我对此问题的回答: 使用LINQ更新集合中的所有对象

使用内置的LINQ表达式是不可能的,但是很容易自己编写代码。 我调用了迭代方法,以便不干扰List .ForEach。

例:

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

迭代来源:

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

好吧,在枚举上没有内置的ForEach扩展方法。 我想知道一个简单的foreach循环可能不容易吗? 尽管如此,写作是微不足道的……

在推动,也许您可​​以有用地使用Where这里:

  foreach (var row in dataGridView.Rows.Cast() .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; } }