What is the correct lambda syntax in C# for looping over each DataGridViewRow of a DataGridView? And as an example lets say the function makes the row .Visible = false based on some value in the Cells[0].
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
See my answer to this question: Update all objects in a collection using LINQ
Thisi s not possible with the built-in LINQ expressions but is very easy to code yourself. I called the method Iterate in order to not interfere with List<T>.ForEach.
Example:
dataGrid.Rows.Iterate(r => {r.Visible = false; });
Iterate Source:
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:
Well, there is no inbuilt ForEach
extension method on enumerable. I wonder if a simple foreach
loop might not be easier? It is trivial to write, though...
At a push, maybe you could usefully use Where
here:
foreach (var row in dataGridView.Rows.Cast<DataGridViewRow>()
.Where(row => (string)row.Cells[0].Value == "abc"))
{
row.Visible = false;
}
But personally, I'd just use a simple loop:
foreach (DataGridViewRow row in dataGridView.Rows)
{
if((string)row.Cells[0].Value == "abc")
{
row.Visible = false;
}
}