I developing an algorithm to read a row from a table (specifically, I'm reading from an Excel file).
I have three conditions about when to terminate the Read operation:
- When an empty cell is found (recognized by an
ElementNotFoundException
- When a cell with errors is found (which corresponds to a null value)
- Both the two previous conditions
This is the current algorithm:
public IEnumerable<string> ReadRow(string spreadsheet, int column, int row, ReadOptions readOptions = ReadOptions.ReadUntilEmpty)
{
var values = new List<string>();
if (readOptions.HasFlag(ReadOptions.ReadUntilEmpty) && readOptions.HasFlag(ReadOptions.ReadUntilCellError))
{
try
{
for (var currentColumn = column; ; currentColumn++)
{
var value = ReadCell(spreadsheet, currentColumn, row);
// Cell has errors, so we exit from the loop
if (value == null) break;
values.Add(value);
}
}
catch (ElementNotFoundException)
{
// The row is terminated
// so we exit the loop withouth loggin any error
}
}
else if (readOptions.HasFlag(ReadOptions.ReadUntilCellError))
{
for (var currentColumn = column; ; currentColumn++)
{
try
{
var value = ReadCell(spreadsheet, currentColumn, row);
// Cell has errors, so we exit from the loop
if (value == null) break;
values.Add(value);
}
catch (ElementNotFoundException)
{
// The ReadOptions is not setted on ReadUntilEmpty
// so we just ignore empty cells
}
}
}
else if (readOptions.HasFlag(ReadOptions.ReadUntilEmpty))
{
try
{
for (var currentColumn = column; ; currentColumn++)
{
var value = ReadCell(spreadsheet, currentColumn, row);
values.Add(value);
}
}
catch (ElementNotFoundException)
{
// The row is terminated
// so we exit the loop withouth loggin any error
}
}
return values;
}
And just for reference, the enumeration used:
[Flags]
public enum ReadOptions
{
ReadUntilEmpty,
ReadUntilCellError
}
How can I improve it?
Also, any idea on how I can reuse this code to read a column instead a row?