[英]C# - Lambda syntax for looping over DataGridView.Rows
C#中用于遍历DataGridView的每个DataGridViewRow的正确lambda语法是什么? 举个例子,假设函数根据Cells [0]中的某个值使行.Visible = false。
好吧,没有可枚举的内置ForEach
扩展方法。 我想知道简单的foreach
循环是否会更容易? 虽然写起来很简单,但是...
一推,也许您可以Where
这里使用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;
}
}
查看我对这个问题的答案: 使用LINQ更新集合中的所有对象
内置的LINQ表达式无法做到这一点,但是您自己编写代码非常容易。 为了不干扰List <T> .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++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.