2

我正在使用电子表格库来访问 excel 文件。

如何通过扩展方法和 lambda 表达式缩短以下构造?我想用布尔值计算所有单元格。

Dictionary<int, Dictionary<int, SLCell>> cells = sl.GetCells();

int nCount = 0;

foreach (Dictionary<int, SLCell> Value in cells.Values)
{
    foreach (SLCell Cell in Value.Values)
    {
        if (Cell.DataType == CellValues.Boolean)
        {
            nCount++;
        }
    }
}
4

1 回答 1

4

您可以为此使用 LINQ:

int ncount = cells.Values.SelectMany(x => x.Values)
                         .Count(x => x.DataType == CellValues.Boolean);

通过SelectMany(x => x.Values)我们创建另一个IEnumerable枚举所有SLCell Cells 的方法。

然后Count(x => x.DataType == CellValues.Boolean)计算 所在的单元格的.DataType数量CellValues.Boolean

于 2017-09-02T17:20:07.827 回答