I am using the spreadsheetlight library to access excel files.
How can I shorten the following construct through extension methods and lambda expressions ? 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:
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.
Then the Count(x => x.DataType == CellValues.Boolean)
counts the number of cells where the .DataType
is CellValues.Boolean
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.