是否可以使 DataGridViewRow.Cells 支持像 Any 或 All 这样的方法?

Is it possible to make DataGridViewRow.Cells support methods like Any or All?

说,我想检查 CellValue 是否是 DataGridView 中的 Row 中的 null。代码使用 foreach 有效。

        foreach (DataGridViewCell c in row.Cells)
        { 
            if (c.Value == null)
            {
                e.Cancel = true;
                MessageBox.Show("empty cell");
            }
        }

我尝试用方法 Any 替换 foreach,但没有编译:

        if(row.Cells.Any(c => c.Value == null))
        {
            e.Cancel = true;
            MessageBox.Show("empty cell");
        }

有没有办法让它支持方法Any

你必须施放它们:

if (row.Cells.Cast<DataGridViewCell>().Any(c => c.Value == null)) {
  // code...
}

DataGridViewCellCollection 未指定泛型类型,因此需要强制转换。见 Enumerable.Cast<TResult> Method:

The Cast(IEnumerable) method enables the standard query operators to be invoked on non-generic collections by supplying the necessary type information. For example, ArrayList does not implement IEnumerable, but by calling Cast(IEnumerable) on the ArrayList object, the standard query operators can then be used to query the sequence.