C# - 用于循环 DataGridView.Rows 的 Lambda 语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/451693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:53:27  来源:igfitidea点击:

C# - Lambda syntax for looping over DataGridView.Rows

c#.netdatagridviewlambda

提问by BuddyJoe

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

在 C# 中循环遍历 DataGridView 的每个 DataGridViewRow 的正确 lambda 语法是什么?作为一个例子,假设函数根据 Cells[0] 中的某个值使行 .Visible = false。

回答by Marc Gravell

Well, there is no inbuilt ForEachextension method on enumerable. I wonder if a simple foreachloop might not be easier? It is trivial to write, though...

好吧,ForEach可枚举没有内置的扩展方法。我想知道一个简单的foreach循环可能不会更容易吗?虽然写起来很琐碎...

At a push, maybe you could usefully use Wherehere:

一推,也许你可以Where在这里有用地使用:

        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;
            }
        }

回答by JaredPar

See my answer to this question: Update all objects in a collection using LINQ

请参阅我对这个问题的回答:使用 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.

这对于内置的 LINQ 表达式是不可能的,但是很容易自己编写代码。我调用方法 Iterate 是为了不干扰 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++;
        }
    }