[英]Extension methods and lambda expressions
I am using the spreadsheetlight library to access excel files. 我正在使用试算表库访问Excel文件。
How can I shorten the following construct through extension methods and lambda expressions ? 如何通过扩展方法和lambda表达式缩短以下构造? I want to count all cells with boolean values.
我想用布尔值计算所有单元格。
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++;
}
}
}
You can use LINQ for this: 您可以为此使用LINQ:
int ncount = cells.Values.SelectMany(x => x.Values)
.Count(x => x.DataType == CellValues.Boolean);
By SelectMany(x => x.Values)
we create another IEnumerable
that enumerates over all SLCell Cell
s. 通过
SelectMany(x => x.Values)
我们创建另一个枚举所有SLCell Cell
的IEnumerable
。
Then the Count(x => x.DataType == CellValues.Boolean)
counts the number of cells where the .DataType
is CellValues.Boolean
. 然后
Count(x => x.DataType == CellValues.Boolean)
计算.DataType
为CellValues.Boolean
的单元格数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.