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].
Asked
Active
Viewed 1.3k times
2 Answers
4
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;
}
}

Marc Gravell
- 1,026,079
- 266
- 2,566
- 2,900
-
That is what I'm doing now (the foreach). Just trying to stretch my brain. In one of my current projects I'm constantly looping over this one DataGridView. It's getting old. LOL – BuddyJoe Jan 16 '09 at 20:22
4
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++;
}
}