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].
A:
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
2009-01-16 19:48:46
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
tyndall
2009-01-16 20:22:53
+1
A:
See my answer to this question: http://stackoverflow.com/questions/398871/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++;
}
}
JaredPar
2009-01-16 19:52:17