【发布时间】:2009-01-16 19:46:23
【问题描述】:
在 C# 中循环遍历 DataGridView 的每个 DataGridViewRow 的正确 lambda 语法是什么?例如,该函数根据 Cells[0] 中的某个值使行 .Visible = false。
【问题讨论】:
标签: c# .net datagridview lambda
在 C# 中循环遍历 DataGridView 的每个 DataGridViewRow 的正确 lambda 语法是什么?例如,该函数根据 Cells[0] 中的某个值使行 .Visible = false。
【问题讨论】:
标签: c# .net datagridview lambda
查看我对这个问题的回答:Update all objects in a collection using LINQ
这对于内置的 LINQ 表达式是不可能的,但是很容易自己编写代码。为了不干扰 List
例子:
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++;
}
}
【讨论】:
好吧,可枚举没有内置的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;
}
}
【讨论】: