2

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++;
        }
    }
}
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
Ron
  • 85
  • 5

1 Answers1

4

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 Cells.

Then the Count(x => x.DataType == CellValues.Boolean) counts the number of cells where the .DataType is CellValues.Boolean.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555