C# - Lambda syntax for looping over DataGridView.R

2019-06-01 01:18发布

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].

2条回答
家丑人穷心不美
2楼-- · 2019-06-01 01:42

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++;
        }
    }
查看更多
Lonely孤独者°
3楼-- · 2019-06-01 02:01

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;
            }
        }
查看更多
登录 后发表回答