Select 在 TableCellCollection 上不可用

Select unavailable on TableCellCollection

编辑:我现在意识到我下面的代码没有多大意义,但我将其保留原样以保留问题。我在下面的回答显示了我试图实现的最终正确代码。

我正在尝试通过 Select 调用在 OnRowDataBound 事件处理程序中的 GridView 上连续修改一些单元格:

e.Row.Cells.AsParallel().Select(c => c.Font.Bold = true);

但我收到以下错误:

'System.Linq.ParallelQuery' does not contain a definition for 'Select'and no 
extension method 'Select' accepting a first argument of type 
'System.Linq.ParallelQuery' could be found (are you missing a using
 directive or an assembly reference?)

我有一个用于 Linq (using System.Linq;) 的 using 指令,如果我有另一个 IEnumerable 类型的对象,Select 方法会在它上面找到而没有错误:

IEnumerable<string> test;
test.Select(s => s);

(显然上面的测试代码会抛出异常,但关键是它编译正确)

为什么我无法在 TableCellCollection 上呼叫 Select

因为 TableCellCollection does not implement generic interface IEnumerable<T>. It implements IEnumerable which is not generic.Since you are using AsParallel on an IEnumerable it uses this overload 其中 returns 一个 IEnumerable。这就是为什么您不能在其上使用 Select 的原因。如果您想获得可枚举的 table 个单元格,您可以投射它们:

e.Row.Cells.Cast<TableCell>().AsParallel()

这将使用 overload 作为 IEnumerable<T> 和 returns ParallelQuery<TSource> 实现 IEnumerable<T>。您将能够对结果使用 Select 或其他 LINQ 方法。

我将 Selman22 的答案标记为正确,因为他解决了我的实际问题,无论我的代码有问题。 为了简洁起见,我也想提供我的最终解决方案。

正如 Selman22 所提到的,在能够访问 LINQ 方法之前,我确实需要先进行 Cast<TableCell>() 调用。

此外,我原来的代码行没有多大意义,因为我显然没有太注意我在做什么。 这是我现在的工作代码:

e.Row.Cells.Cast<TableCell>().Where(c => c.Font.Bold == true).ToList().ForEach(c => c.ForeColor = Color.Red);